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程序的方法

如何运行Python程序的方法

安装完python之后,我们可以做两件事情, 1.将安装目录中的Doc目录下的python331.chm使用手册复制到桌面上,方便学习和查阅 2.将Python安装路径我的是C:\Pyt...

pip和pygal的安装实例教程 原创

pip和pygal的安装实例教程 原创

本文分为两个部分,第一部分是关于pip,第二部分关于pygal,主要关于二者的简介以及安装过程的分享,希望对大家有所帮助。 一、pip 1.简介 pip 是一个安装和管理 Python...

Python 实现顺序高斯消元法示例

Python 实现顺序高斯消元法示例

我就废话不多说,直接上代码吧! # coding: utf8 import numpy as np # 设置矩阵 def getInput(): matrix_a = np.m...

Django ORM 查询管理器源码解析

ORM 查询管理器 对于 ORM 定义: 对象关系映射, Object Relational Mapping, ORM, 是一种程序设计技术,用于实现面向对象编程语言里不同类型系统的数...

python实现文件的备份流程详解

python实现文件的备份流程详解

python实现输入要备份的文件名称:test.txt 12行代码实现文件备份功能 第一步:打开我们的pycharm软件,然后新建一个Python文件 第二步:新建好我们的Python文...