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生成n个元素的全组合方法

利用二进制反格雷码(bynary reflected Gray code)的方式生成n个元素的全组合,Cn1+Cn2+...+Cnn, 如在利用穷举方法解决背包问题时,就需要找出物品的所...

VSCode下配置python调试运行环境的方法

VSCode下配置python调试运行环境的方法

VSCode配置python调试环境 很久之前的一个东东,翻出来看看 VSCode配置python调试环境 * 1.下载python解释器 * 2.在V...

Python的内存泄漏及gc模块的使用分析

一般来说在 Python 中,为了解决内存泄漏问题,采用了对象引用计数,并基于引用计数实现自动垃圾回收。 由于Python 有了自动垃圾回收功能,就造成了不少初学者误认为自己从此过上了好...

softmax及python实现过程解析

softmax及python实现过程解析

相对于自适应神经网络、感知器,softmax巧妙低使用简单的方法来实现多分类问题。 功能上,完成从N维向量到M维向量的映射 输出的结果范围是[0, 1],对于一个sample的...

详解Python中用于计算指数的exp()方法

 exp()方法返回指数x: ex. 语法 以下是exp()方法的语法: import math math.exp( x ) 注意:此函数是无法直接访问的,所以我们...