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

相关文章

python3实现用turtle模块画一棵随机樱花树

python3实现用turtle模块画一棵随机樱花树

废话不多说了,直接上代码吧! #!/usr/bin/env python # coding=utf-8 # 画一棵樱花 import turtle import random...

【Python】Python的urllib模块、urllib2模块批量进行网页下载文件

【Python】Python的urllib模块、urllib2模块批量进行网页下载文件

由于需要从某个网页上下载一些PDF文件,但是需要下载的PDF文件有几百个,所以不可能用人工点击来下载。正好Python有相关的模块,所以写了个程序来进行PDF文件的下载,顺便熟悉了Pyt...

django 实现celery动态设置周期任务执行时间

django 实现celery动态设置周期任务执行时间

蓝鲸paas平台app开发经验分享 腾讯蓝鲸智云是一套基于PaaS的技术解决方案,提供了完善的前后台开发框架、调度引擎、公共组件等模块,帮助业务的产品和技术人员快速构建低成本、免运维的支...

获取python的list中含有重复值的index方法

关于怎么获得,我想其实网上有很多答案。 list.index( )获得值的索引值,但是如果list中含有的值一样,例如含有两个11,22,这样每次获得的都是第一个值的位置。 那么怎么去解...

Opencv+Python实现图像运动模糊和高斯模糊的示例

Opencv+Python实现图像运动模糊和高斯模糊的示例

运动模糊:由于相机和物体之间的相对运动造成的模糊,又称为动态模糊 Opencv+Python实现运动模糊,主要用到的函数是cv2.filter2D(): # coding: utf-...