Beautiful Soup parses anything you give it, and does the tree traversal stuff for you.
BeautifulSoup也叫美味汤,他是一个非常优秀的python第三方库,它能够对html、xml格式进行解析,并且提取其中的相关信息。在BeautifulSoup的网站上有这样一番话,BeautifulSoup可以对你提供给他的任何格式进行相关的爬取,并且可以进行树形解析。
BeautifulSoup的使用原理是它能够把任何你给它的文档当做一锅汤,然后给你煲制这锅汤。
安装BeautifulSoup
用管理员权限启动命令行,然后我们在命令行上执行如下命令:
pip install beautifulsoup4
测试页面
BeautifulSoup就下载安装完成了,然后我们对比BeautifulSoup来个小测。这里边我们使用一个html页面,
地址是http://www.yeahcoding.tech/python/demo.html 我们用浏览器先打开这个网站看一下。
在这个页面中我们看到它有一个标题栏,上面有一行字,叫this is a python demo,这个地方表示的是一个title信息,我们可以将这个文件存取下来,生成dem.html或者我们用它的源代码。
我们打开它的源代码,能看到这个页面对应的是一个html5格式的代码,在代码中我们看到了很多的标签,这种标签以一对尖括号来表示。
Requests库获取页面源码
我们已经学过了Requests库,可以用Requests库来自动的获得这个链接对应的源代码。
>>> import requests
>>> r = requests.get('http://www.yeahcoding.tech/python/demo.html')
>>> r.text
'\n
This is a python demo page\n\nThe demo python introduces several python courses.
\nPython is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\nPython Crawler .
\n'>>>
使用BeautifulSoup库
下面我来对beatifulsoup的安装进行小测。
>>> demo = r.text
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo, 'html.parser')
>>> print(soup.prettify)
This is a python demo page
The demo python introduces several python courses.
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
>
>>>
尽管我们安装这个库的时候安装的是beautifulsoup4,但是我们在使用的时候,我们可以用它的简写bs4,所以我们使用from bs4 import BeautifulSoup引入了BeautifulSoup类。
然后,我们把这个demo的页面熬成一个BeautifulSoup能够理解的汤。除了给出demo,同时还要给出一个解析demo的解释器,这里边我们的解释器使用的是html.parser,也就是说我们是对demo进行html的解析。
那下面我们看看我们解析是否正确,也就是看一下BeautifulSoup库安装是否正确,用Print语句将我们做的这锅汤打印出来。
总结
使用BeautifulSoup库简单来说只需要两行代码:
from bs4 import BeautifulSoup
soup = BeautifulSoup(‘
data
’)BeautifulSoup类有两个参数,第一个参数是我们需要解析的一个HTML格式的信息,使用
data
表示;第二个参数是解析器,我们这里使用的html.parser。只有两个代码,我们就可以解析我们看到的html的信息,是不是很简单呢!