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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

使用C语言扩展Python程序的简单入门指引

一、简介 Python是一门功能强大的高级脚本语言,它的强大不仅表现在其自身的功能上,而且还表现在其良好的可扩展性上,正因如此,Python已经开始受到越来越多人的青睐,并且被屡屡成功地...

在django模板中实现超链接配置

django中的超链接,在template中可以用{% url 'app_name:url_name' param%} 其中app_name在工程urls中配置的namespace取值,...

浅谈numpy数组中冒号和负号的含义

在实际使用numpy时,我们常常会使用numpy数组的-1维度和”:”用以调用numpy数组中的元素。也经常因为数组的维度而感到困惑。 总体来说,”:”用以表示当前维度的所有子模块 “-...

Python中使用异常处理来判断运行的操作系统平台方法

代码实例: 复制代码 代码如下: try:     import termios, TERMIOS               1 except Impor...

python函数与方法的区别总结

(1)函数的分类: 内置函数:python内嵌的一些函数。 匿名函数:一行代码实现一个函数功能。 递归函数 自定义函数:根据自己的需求,来进行定义函数。 (2)方法的分类: 普通方法:直...