BeautifulSoup库的简介
也称“美味汤”,是非常优秀的python第三方库,能够对html xml格式进行解析并提取其中的相关信息
以“管理员身份”启动command命令台
pip install beautifulsoup4
安装测试例
演示HTML页面地址:https://python123.io/ws/demo.html
获取源代码:
- 打开浏览器找到当前页面 右键点击查看页面源代码
- 使用requests库自动地获得链接对应的源代码
import requests
r = requests.get('http://python123.io/ws/demo.html')
r.text
# 为了简化定义demo表示这个页面的所有内容
demo = r.text
结果:
测试:
# 导入BeautifulSoup库
# BeautifulSoup4简写bs4
# from bs4导入BeautifulSoup类
from bs4 import BeautifulSoup
# html.parser为解析demo的解析器 对demo进行html的解析
soup = BeautifulSoup(demo, 'html.parser')
# 查看解析是否正确,即库的安装是否正确,使用print语句打印
print(soup.prettify())
结果: