BeautifulSoup使用简介

Beautiful Soup 安装

1
easy_install beautifulsoup4
1
pip install beautifulsoup4

创建 Beautiful Soup 对象

首先必须要导入 bs4 库

1
from bs4 import BeautifulSoup
1
2
3
4
5
6
7
8
9
10
11
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
"""

创建 beautifulsoup 对象

1
soup = BeautifulSoup(html)

另外,我们还可以用本地 HTML 文件来创建对象,例如

1
soup = BeautifulSoup(open('index.html'))

上面这句代码便是将本地 index.html 文件打开,用它来创建 soup 对象 下面我们来打印一下 soup 对象的内容,格式化输出

1
print soup.prettify()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title" name="dromouse">
<b>
The Dormouse's story
</b>
</p>
<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>
<p class="story">
...
</p>
</body>
</html>

基本使用

标签选择器

在快速使用中我们添加如下代码:

1
2
3
4
print(soup.title)
print(type(soup.title))
print(soup.head)
print(soup.p)

通过这种 soup.标签名 我们就可以获得这个标签的内容
这里有个问题需要注意,通过这种方式获取标签,如果文档中有多个这样的标签,返回的结果是第一个标签的内容,如上面我们通过 soup.p 获取 p 标签,而文档中有多个 p 标签,但是只返回了第一个 p 标签内容

获取名称

当我们通过 soup.title.name 的时候就可以获得该 title 标签的名称,即 title

获取属性

1
2
print(soup.p.attrs['name'])
print(soup.p['name'])

上面两种方式都可以获取 p 标签的 name 属性值

获取内容

1
print(soup.p.string)

结果就可以获取第一个 p 标签的内容:
The Dormouse’s story

嵌套选择

我们直接可以通过下面嵌套的方式获取

1
print(soup.head.title.string)

子节点和子孙节点
contents 的使用
通过下面例子演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
html = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<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">
<span>Elsie</span>
</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>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(html,'lxml')
print(soup.p.contents)

结果是将 p 标签下的所有子标签存入到了一个列表中

列表中会存入如下元素

children 的使用

通过下面的方式也可以获取 p 标签下的所有子节点内容和通过 contents 获取的结果是一样的,但是不同的地方是 soup.p.children 是一个迭代对象,而不是列表,只能通过循环的方式获取素有的信息

1
2
3
print(soup.p.children)
for i,child in enumerate(soup.p.children):
print(i,child)

通过 contents 以及 children 都是获取子节点,如果想要获取子孙节点可以通过 descendants
print(soup.descendants)同时这种获取的结果也是一个迭代器

父节点和祖先节点

通过 soup.a.parent 就可以获取父节点的信息

通过 list(enumerate(soup.a.parents))可以获取祖先节点,这个方法返回的结果是一个列表,会分别将 a 标签的父节点的信息存放到列表中,以及父节点的父节点也放到列表中,并且最后还会讲整个文档放到列表中,所有列表的最后一个元素以及倒数第二个元素都是存的整个文档的信息

兄弟节点

soup.a.next_siblings 获取后面的兄弟节点
soup.a.previous_siblings 获取前面的兄弟节点
soup.a.next_sibling 获取下一个兄弟标签
souo.a.previous_sinbling 获取上一个兄弟标签

1
get_text()

如果只想得到 tag 中包含的文本内容,那么可以调用 get_text() 方法,这个方法获取到 tag 中包含的所有文版内容包括子孙 tag 中的内容,并将结果作为 Unicode 字符串返回

1
2
3
4
5
6
7
markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup)

soup.get_text()
u'\nI linked to example.com\n'
soup.i.get_text()
u'example.com'

可以通过参数指定 tag 的文本内容的分隔符:

1
2
# soup.get_text("|")
u'\nI linked to |example.com|\n'

还可以去除获得文本内容的前后空白:

1
2
# soup.get_text("|", strip=True)
u'I linked to|example.com'

或者使用 .stripped_strings 生成器,获得文本列表后手动处理列表:

1
2
[text for text in soup.stripped_strings]
# [u'I linked to', u'example.com']

.string

如果 tag 只有一个 NavigableString 类型子节点,那么这个 tag 可以使用 .string 得到子节点:

1
2
title_tag.string
# u'The Dormouse's story'

如果一个 tag 仅有一个子节点,那么这个 tag 也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同:

1
2
3
4
head_tag.contents
# [<title>The Dormouse's story</title>]
head_tag.string
# u'The Dormouse's story'

如果 tag 包含了多个子节点,tag 就无法确定 .string 方法应该调用哪个子节点的内容, .string 的输出结果是 None :

1
2
print(soup.html.string)
# None

BeautifulSoup使用简介
http://jhayes.cn/blog/3873777087.html
作者
JHAYES
发布于
2017年11月7日
许可协议