|
发表于 2023-11-12 14:15:07
|
显示全部楼层
BeautifulSoup是一个Python库,用于从HTML或XML文件中提取数据。它提供了一种简单的方式来浏览文档树,并搜索特定的标记或数据。下面是一些基本的用法和函数:
1. 解析HTML/XML文档:
- from bs4 import BeautifulSoup
- # 从文件中解析
- with open("index.html") as file:
- soup = BeautifulSoup(file, 'html.parser')
- # 从字符串解析
- soup = BeautifulSoup("<html>data</html>", 'html.parser')
复制代码
2. 搜索标记:
- # 通过标记名搜索
- soup.find_all('a') # 查找所有的<a>标记
- # 通过CSS类名搜索
- soup.find_all(class_='class_name')
- # 通过id搜索
- soup.find_all(id='id_name')
复制代码
3. 提取数据:
- # 获取标记内容
- tag.string
- # 获取标记属性
- tag['attribute_name']
复制代码
4. 遍历文档树:
- # 遍历子节点
- for child in tag.children:
- print(child)
- # 遍历父节点
- for parent in tag.parents:
- print(parent)
复制代码
以上是BeautifulSoup库的一些基本用法和函数,希望能帮助到你! |
|