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

相关文章

python UDP(udp)协议发送和接收的实例

需要建立2个文件,一个作为客户端,一个作为服务端 文件一 作为客户端client,文件二作为服务端server udp的特点是不需要建立连接 文件一客户端 #不需要建立连接 impo...

python中反射用法实例

本文实例讲述了python中反射用法。分享给大家供大家参考。具体如下: import sys, types,new def _get_mod(modulePath): try:...

python结合API实现即时天气信息

python结合API实现即时天气信息

python结合API实现即时天气信息 import urllib.request import urllib.parse import json """ 利用“最美天气”抓取...

用Python编写一个简单的FUSE文件系统的教程

如果你是我的长期读者,那么你应该知道我在寻找一个完美备份程序,最后我写了一个基于bup的我自己的加密层。 在写encbup的时候,我对仅仅恢复一个文件就必须要下载整个巨大的档案文件的做法...

利用Python如何实现数据驱动的接口自动化测试

利用Python如何实现数据驱动的接口自动化测试

前言 大家在接口测试的过程中,很多时候会用到对CSV的读取操作,本文主要说明Python3对CSV的写入和读取。下面话不多说了,来一起看看详细的介绍吧。 1、需求 某API,GET方法,...