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

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

相关文章

python3中的eval和exec的区别与联系

看了很多网上的方法,写入文件后打开文件看确实不再是乱码,但是从文件中读入json时发现了乱码,可能是读文件默认的编码格式不对。下面读写方法可行。 注意,ensure_ascii=Fals...

python递归函数绘制分形树的方法

python递归函数绘制分形树的方法

分形几何学的基本思想:客观事物具有自相似性的层次结构,局部和整体在形态,功能,信息,时间,空间等方面具有统计意义上的相似性,称为自相似性,自相似性是指局部是整体成比例缩小的性质。 我们先...

Python计算库numpy进行方差/标准方差/样本标准方差/协方差的计算

使用numpy可以做很多事情,在这篇文章中简单介绍一下如何使用numpy进行方差/标准方差/样本标准方差/协方差的计算。 variance: 方差 方差(Variance)是概率论中最基...

python try except 捕获所有异常的实例

如下所示: try: a=1 except Exception as e: print (e) import traceback import sys try: a = 1...

Python函数的参数常见分类与用法实例详解

本文实例讲述了Python函数的参数常见分类与用法。分享给大家供大家参考,具体如下: 1.形参与实参是什么? 形参(形式参数):指的是 在定义函数时,括号内定义的参数,形参其实就是变量名...