python使用BeautifulSoup分析网页信息的方法

yipeiwu_com6年前Python基础

本文实例讲述了python使用BeautifulSoup分析网页信息的方法。分享给大家供大家参考。具体如下:

这段python代码查找网页上的所有链接,分析所有的span标签,并查找class包含titletext的span的内容

复制代码 代码如下:
#import the library used to query a website
import urllib2

#specify the url you want to query
url = "http://www.python.org"

#Query the website and return the html to the variable 'page'
page = urllib2.urlopen(url)

#import the Beautiful soup functions to parse the data returned from the website
from BeautifulSoup import BeautifulSoup

#Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup = BeautifulSoup(page)

#to print the soup.head is the head tag and soup.head.title is the title tag
print soup.head
print soup.head.title

#to print the length of the page, use the len function
print len(page)

#create a new variable to store the data you want to find.
tags = soup.findAll('a')

#to print all the links
print tags

#to get all titles and print the contents of each title
titles = soup.findAll('span', attrs = { 'class' : 'titletext' })
for title in allTitles:
print title.contents

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python执行精确的小数计算方法

在进行浮点数计算时它们无法精确表达出所有的十进制小数位。 a = 4.1 b = 5.329 print(a+b) 9.428999999999998 这些误差实际上是底层CP...

Python 私有化操作实例分析

Python 私有化操作实例分析

本文实例讲述了Python 私有化操作。分享给大家供大家参考,具体如下: 私有化 xx: 公有变量 _x: 单前置下划线,私有化属性或方法,from somemodule import...

django框架如何集成celery进行开发

django框架如何集成celery进行开发

上一篇已经介绍了celery的基本知识,本篇以一个小项目为例,详细说明django框架如何集成celery进行开发。 本系列文章的开发环境: window 7 + python2.7...

python实现通过flask和前端进行数据收发

python代码: # -*- coding: utf-8 -*- from flask import Flask,jsonify,render_template,request i...

对numpy中布尔型数组的处理方法详解

布尔数组的操作方式主要有两种,any用于查看数组中是否有True的值,而all则用于查看数组是否全都是True。 如果用于计算的时候,布尔量会被转换成1和0,True转换成1,False...