学习自bs4官方文档https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

1
2
3
4
5
6
7
8
9
# 安装bs4库
pip install beautifulsoup4

from bs4 import BeautifulSoup

#解析网页,创建BeautifulSoup对象
#第一个参数为网页代码
#第二个参数为解析器
soup = BeautifulSoup(html_doc, 'html.parser')

BeautifulSoup处理后,对象可分为四种类型:Tag, NavigableString, BeautifulSoup, Comment

Tag类型

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 获得a标签(其余同理)
tag = soup.a

# 获得标签名字
# 若改变该名字,soup中所有该标签名字都将改变
tag.name

# 获取标签属性
# 属性可以被修改
tag[&#