By 一页编程
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
'\nThis 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:
Python Crawler .