python插件之beautifulsoup
时间:2010-09-20 来源:niuniu2006t
Beautiful Soup 是 Python 内置的网页分析工具,名字叫美丽的蝴蝶,是一个可以快速地解析网页内容的Python HTML/XML 解析器。
重要特性:
- 可接受损坏的标签文档,在内部生成一棵剖析树,并尽可能和你的原文档一致。通常可以满足搜集数据的需求。
- 提供和python语法相近的命令来查找、编辑。它提供一个工具集帮助你解析并解释出你需要的内容。这样你就不必为每一个应用创建自己的解析工具。
- 自动将传进来的文档转换为 Unicode 编码 ,输出的时候转换为 UTF-8。可以解析任何你提供的文档,做解析的事情。你可以命令他“找出所有的链接",或者"找出所有 class 是 externalLink 的链接",或是"找出所有的 url 匹配正则表达式 ”foo.com" 的链接,甚至可以是这样的命令---“找出那些表头是粗体文字,然后返回给我文字”。
在 BeautifulSoup 的帮助下,原本要花数个小时的工作,通过 Beautiful Soup 几分钟即可搞定。
下面让我们看看几个样例。
from BeautifulSoup import BeautifulSoup #解析HTML
from BeautifulSoup import BeautifulStoneSoup #解析XML
import BeautifulSoup #获取任何信息
下面使用一段代码演示Beautiful Soup的基本使用方式。你可以拷贝与粘贴这段代码自己运行。
下面是一个解析文档的方法:
soup.contents[0].name
# u'html'
soup.contents[0].contents[0].name
# u'head'
head = soup.contents[0].contents[0]
head.parent.name
# u'html'
head.next
#<title>Page title</title>
head.nextSibling.name
# u'body'
head.nextSibling.contents[0]
#<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
head.nextSibling.contents[0].nextSibling
#<p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
接着是一打方法查找文档中包含的标签,或者含有指定属性的标签
titleTag = soup.html.head.title
titleTag
#<title>Page title</title>
titleTag.string
# u'Page title'
len(soup('p'))
# 2
soup.findAll('p', align="center")
# [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>]
soup.find('p', align="center")
#<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
soup('p', align="center")[0]['id']
# u'firstpara'
soup.find('p', align=re.compile('^b.*'))['id']
# u'secondpara'
soup.find('p').b.string
# u'one'
soup('p')[1].b.string
# u'two'
当然也可以简单地修改文档
titleTag['id'] = 'theTitle'
titleTag.contents[0].replaceWith("New title")
soup.html.head
# <head><title id="theTitle">New title</title></head>
soup.p.extract()
soup.prettify()
# <html>
# <head>
# <title id="theTitle">
# New title
# </title>
# </head>
# <body>
# <p id="secondpara" align="blah">
# This is paragraph
# <b>
# two
# </b>
# .
# </p>
# </body>
# </html>
soup.p.replaceWith(soup.b)
# <html>
# <head>
# <title id="theTitle">
# New title
# </title>
# </head>
# <body>
# <b>
# two
# </b>
# </body>
# </html>
soup.body.insert(0, "This page used to have ")
soup.body.insert(2, " <p> tags!")
soup.body
# <body>This page used to have <b>two</b> <p> tags!</body>
最后,为大家提供 Beautiful Soup 的文档。希望能对您有帮助。
英文原文:http://www.crummy.com/software/BeautifulSoup/ (翻译有删节,请查看原文链接)