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

相关文章

解决Pytorch 训练与测试时爆显存(out of memory)的问题

Pytorch 训练时有时候会因为加载的东西过多而爆显存,有些时候这种情况还可以使用cuda的清理技术进行修整,当然如果模型实在太大,那也没办法。 使用torch.cuda.empty_...

python用列表生成式写嵌套循环的方法

将两个嵌套for循环写成一个列表生成式 如,有一个嵌套列表,a=[[1,2],[3,4],[5,6]],要提取列表里的每一个元素 用for循环处理: for i in a: fo...

python将字母转化为数字实例方法

python将字母转化为数字实例方法

python如何将字母转化为数字? 将英文字母转成数字: 转换 ord('F') 反转 chr(70) python ord() 函数 是 chr() 函数(...

python使用Tkinter显示网络图片的方法

本文实例讲述了python使用Tkinter显示网络图片的方法。分享给大家供大家参考。具体实现方法如下: ''' tk_image_view_url_io.py display an...

python excel使用xlutils类库实现追加写功能的方法

由于近日写工作汇报 交一份概要和 excel版本 发现手写 太麻烦 想写个代码来自动 读取一个文本中的所有内容 按需求写入 对应excel和概要中 自动完成 就找了找python 的类库...