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 实现网上商城,转账,存取款等功能的信用卡系统

python 实现网上商城,转账,存取款等功能的信用卡系统

一、要求 二、思路 1.购物类buy 接收 信用卡类 的信用卡可用可用余额, 返回消费金额 2.信用卡(ATM)类 接收上次操作后,信用卡可用余额,总欠款,剩余欠款,存款 其中: 1...

浅析Python中else语句块的使用技巧

浅析Python中else语句块的使用技巧

学过C/C++的都知道,else语句是和if语句搭配使用的,但是在Python中,else语句更像是作为一个模块,不仅仅可以和if语句搭配,还可以和循环语句,异常处理语句搭配使用。 下面...

用Python去除图像的黑色或白色背景实例

用Python去除图像的黑色或白色背景实例

用Python去除背景,得到有效的图像 此目的是为了放入深度学习计算中来减少计算量,同时突出特征,原图像为下图,命名为1.jpg,在此去除白色背景,黑色背景同理 需要对原图像进行的处理...

python实现列表中最大最小值输出的示例

如下所示: def findMinAndMax(L): maxL = None minL = None if L: maxL = L[0] minL =...

Android应用开发中Action bar编写的入门教程

从Android 3.0开始除了我们重点讲解的Fragment外,Action Bar也是一个重要的内容,Action Bar主要是用于代替传统的标题栏,对于Android平板设备来说屏...