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

相关文章

解决Django中多条件查询的问题

tags: django中对条件查询 一些cms项目都会使用到多条件查询,我们后端如何处理请求的条件呢? 满足一个条件 满足两个条件 满足多个条件 …………………. 这样处理起来...

python编程实现希尔排序

python编程实现希尔排序

观察一下”插入排序“:其实不难发现她有个缺点:   如果当数据是”5, 4, 3, 2, 1“的时候,此时我们将“无序块”中的记录插入到“有序块”时,估计俺们要崩盘,每次插入都要移动位置...

Python代码的打包与发布详解

在python程序中,一个.py文件被当作一个模块,在各个模块中定义了不同的函数。当我们要使用某一个模块中的某一个函数时,首先须将这个模块导入,否则就会出现函数未定义的情况. 下面记录的...

使用PYTHON创建XML文档

当用GOOGLE查的时候,内容几乎都是一样的。但是你想要的东西,一个也没有。例如,我就找不到中国人写的如何使用PYTHON来创建一个XML文件。当然,直接用文件写的方式也能够达到同样的效...

Python中py文件转换成exe可执行文件的方法

Python中py文件转换成exe可执行文件的方法

一、背景 今天闲着无事,写了一个小小的Python脚本程序,然后给同学炫耀的时候,发现每次都得拉着其他人过来看着自己的电脑屏幕,感觉不是很爽,然后我想着网上肯定有关于Python脚本转...