我是靠谱客的博主 魔幻超短裙,这篇文章主要介绍python3与Beautiful Soup库,现在分享给大家,希望可以做个参考。

BeautifulSoup库主要用于处理HTML和XML格式的文件,常用于网络爬虫。
但是BeautifulSoup库的3版本已不再更新,所以现在主要来说下4版本及之后的版本。
首先是安装:
安装文件在这里:
使用pip 安装4版本时要注意应该用

复制代码
1
pip install bs4

然后就是库的引用格式的改变:
3版本:

复制代码
1
2
3
4
5
6
from BeautifulSoup import BeautifulSoup # For processing HTML from BeautifulSoup import BeautifulStoneSoup # For processing XML import BeautifulSoup # To get everything

4版本:

复制代码
1
2
import bs4 # To get everything

在使用时也有一些差别。具体可参照这里,要注意的是这里的示例是在python2中的,需要自行转换成python3(示例中仅仅只需要把print后的内容加上小括号就可以运行了)。而且示例是基于3版本的。
例如实例中:

复制代码
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
from BeautifulSoup import BeautifulSoup import re doc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '</html>'] soup = BeautifulSoup(''.join(doc)) print soup.prettify() # <html> # <head> # <title> # Page title # </title> # </head> # <body> # <p id="firstpara" align="center"> # This is paragraph # <b> # one # </b> # . # </p> # <p id="secondpara" align="blah"> # This is paragraph # <b> # two # </b> # . # </p> # </body> # </html>

我们在4版本中就应该改为

复制代码
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
from bs4 import BeautifulSoup import re doc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '</html>'] soup = BeautifulSoup(''.join(doc)) print(soup.prettify()) # <html> # <head> # <title> # Page title # </title> # </head> # <body> # <p align="center" id="firstpara"> # This is paragraph # <b> # one # </b> # . # <p align="blah" id="secondpara"> # This is paragraph # <b> # two # </b> # . # </p> # </p> # </body> #</html>

可以看出输出是有一些差别的,体现在第一个 < /b >出现的位置,还有一些小差别就自己探索吧。
还有一点就是4版本中处理HTML和XML只需要一个函数就可以了,而不需要3版本中的BeautifulSoup和BeautifulStoneSoup两个函数分别处理。

最后

以上就是魔幻超短裙最近收集整理的关于python3与Beautiful Soup库的全部内容,更多相关python3与Beautiful内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部