Python工具篇之Beautiful Soup

1. Beautiful Soup的简介

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.Beautiful Soup 3 目前已经停止开发,我们推荐在现在的项目中使用Beautiful Soup 4, 移植到BS4,出现的例子在Python2.7和Python3.2中的执行结果相同

2.使用的示例代码

安装代码

sudo easy_install -U beautifulsoup4

下面的一段HTML代码将作为例子被多次用到.这是 爱丽丝梦游仙境的 的一段内容

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

常见的元素输出

#第一个参数是html对象
soup=BeautifulSoup(html,"lxml")
#输出<title>的元素
print soup.title
#输出<head>的元素
print soup.head
#输出<a>的元素
print soup.a
#输出<p>的元素
print soup.p
#输出name的元素
print soup.name
#输出head的name属性
print soup.head.name
#输出p元素的属性和对印值得到字典
print soup.p.attrs
#输出p元素的里面的class属性
print soup.p['class']
print soup.p.get('class')
#修改class属性内容
soup.p['class']="newClass"
print soup.p
#获取标签内容
print soup.p.string
#输出所有head属性的一个数组
print soup.head.contents
#遍历所有body的子节点
for child in soup.body.children:
    print child
for child in soup.descendants:
    print child

string 、strings和stripped_strings的效果

print soup.head.string  
    #The Dormouse's story
print soup.title.string
    #The Dormouse's story
#获取多个内容,遍历获取所有元素
for string in soup.strings:
    print(repr(string))
    # u"The Dormouse's story"
    # u'\n\n'
    # u"The Dormouse's story"
    # u'\n\n'
    # u'Once upon a time there were three little sisters; and their names were\n'
    # u'Elsie'
    # u',\n'
    # u'Lacie'
    # u' and\n'
    # u'Tillie'
    # u';\nand they lived at the bottom of a well.'
    # u'\n\n'
    # u'...'
    # u'\n
#输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
for string in soup.stripped_strings:
    print(repr(string))
    #u'Once upon a time there were three little sisters; and their names were'
    #u','
    #u'Lacie'   
    #u'and'
    #u'Tillie'
    #u';\nand they lived at the bottom of a well.'

输出父节点parent、parents

content=soup.head.title.string
print content.parent.name
#title
for parent in content.parents:
    print parent.name
    #title
    #head
    #html
    #[document]

兄弟节点next_sibling和prev_sibling

print soup.p.next_sibling
#
#
#
print soup.p.prev_sibling
#None
print soup.p.next_sibling.next_sibling
#<p class="story">Once upon a time there were three little sisters; and their names were
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
#<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
#<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

搜索文档树
函数原型

find_all( name , attrs , recursive , string , **kwargs )
find_parents( name , attrs , recursive , string , **kwargs )
find_parent( name , attrs , recursive , string , **kwargs )
。。。

1.name查找所有名为name的tag

soup=BeautifulSoup(html,"lxml")
print soup.find_all('p')
#[<p class="title" name="dromouse"><b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little si
sters; and their names were\n<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,\n<a class="sister
" href="http://example.com/lacie" id="link2">Lacie</a> and\n<a class="sister" href="http://example.com/tillie" id="link3">Tilli
e</a>;\nand they lived at the bottom of a well.</p>]

2.传入正则表达

soup=BeautifulSoup(html,"lxml")
for tag in soup.find_all(re.compile("b.*?")):
    print(tag.name)
    #body
    #b

3.传入数组

soup=BeautifulSoup(html,"lxml")
#包含a,b标签
print soup.find_all(["a","b"])  
#[<b>The Dormouse's story</b>, <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister
" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a
>]

4.传入True

#所有节点
soup=BeautifulSoup(html,"lxml")
for tag in soup.find_all(True):
    print tag.name 
    #html
    #head
    #title
    #body
    #p
    #b
    #p
    #a
    #a
    #a

5.传入方法

#含有class而没有href的tag
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('href')
print soup.find_all(has_class_but_no_id)
#[<p class="title" name="dromouse"><b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little si
sters; and their names were\n<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,\n<a class="sister
" href="http://example.com/lacie" id="link2">Lacie</a> and\n<a class="sister" href="http://example.com/tillie" id="link3">Tilli
e</a>;\nand they lived at the bottom of a well.</p>]

6.传入字典

soup=BeautifulSoup(html,"lxml")
#id含有link2项的
print soup.find_all(id='link2') 
#[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
#href中含有elsie项
print soup.find_all(href=re.compile("elsie"))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
#href含有elsie项并且id为link1项
print soup.find_all(href=re.compile("elsie"),id='link1') 
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

中文文档

http://beautifulsoup.readthedocs.io/zh_CN/latest/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容