首先我们安装一下 Beautiful Soup库:
以管理员身份运行命令提示符,输入pip install beautifulsoup4
:
Beautiful Soup库简介:
Beautiful Soup库能够对HTML、XML格式进行解析,并且提取其中的相关信息。
Beautiful Soup库可以对你提供给它的任何格式进行相关的爬取,并且可以进行树形解析。
Beautiful Soup库使用原理:把我们给它的文档当作一锅汤,然后煲制这锅汤。
Beautiful Soup库小测:
演示HTML页面地址:http://python123.io/ws/demo.html
![](https://i-blog.csdnimg.cn/blog_migrate/c0ab5f74800fcf1a2d2873cecf276295.png)
如何获得页面源代码?
一、手工获得,在浏览器打开页面,查看源代码。
二、用 requests库来自动获得链接对应的源代码。
import requests
r = requests.get("https://python123.io/ws/demo.html")
print(r.text)
Output:
![](https://i-blog.csdnimg.cn/blog_migrate/90912f3e26a0c5753f0884857fb47019.png)
获得源代码后,我们用Beautiful Soup库进行解析:
import requests
from bs4 import BeautifulSoup
r = requests.get("https://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, "html.parser")
print(soup.prettify())
Output:
<html>
<head>
<title>
This is a python demo page
</title>
</head>
<body>
<p class="title">
<b>
The demo python introduces several python courses.
</b>
</p>
<p class="course">
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
Basic Python
</a>
and
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
Advanced Python
</a>
.
</p>
</body>
</html>
这说明 BeautifulSoup库成功解析了我们给出的demo页面。
怎么使用Beautiful Soup库呢?
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>', 'html.parser')
BeautifulSoup 是一个类
第一个参数是我们需要 BeautifulSoup 解析的一个 html 格式的信息
html.parser 是解析器
参考资料:Python网络爬虫与信息提取(北京理工大学慕课)