Beautiful Soup第三方库的安装
pip install Beautifulsoup4
python中使用BeautifulSoup
import bs4
# 或者
from bs4 import BeautifulSoup
网页解析器语法
- 创建BeautifulSoup对象
from bs4 import BeautifulSoup
# 根据html网页字符串创建BeautifulSoup对象
soup = BeautifulSoup(
html_doc, # htmll文档字符串
'html.parser', # html解析器
from_encoding='utf8' # html文档的编码
)
- 搜索节点(find_all,find)
find_all(name,attrs,string)
# name:节点名称
# attrs:节点属性
# string:节点的文本
# 查找所有标签为a的节点
soup.find_all('a')
# 查找所有标签为a,链接符合/view/test123.html形式的节点
soup.find_all('a',href='/view/test123.html')
# 查找所有标签为div,class为abc,文字为spider的节点
soup.find_all('div',class_='abc',string="spider")
- 访问节点信息
# 得到节点: <a href="test123.html">Spider</a>
# 获取查找到的节点的标签名称
node.name
# 获取查找到的a节点的href属性
node['href']