要使用 Python 爬虫获取标签,可借助 BeautifulSoup 库:导入 BeautifulSoup获取 HTML 文档创建 BeautifulSoup 对象根据标签名称或属性查找标签提取标签内容(文本、HTML、属性)

如何使用 Python 爬虫获取标签
在 Python 爬虫中获取标签非常方便。这可以通过使用 BeautifulSoup 库来轻松实现,该库是一个用于从 HTML 和 XML 文档中解析数据的库。
步骤:
-
导入 BeautifulSoup:
立即学习“Python免费学习笔记(深入)”;
<code>from bs4 import BeautifulSoup</code>
-
获取 HTML 文档:
-
使用
requests库获取 HTML 文档:<code>import requests response = requests.get('https://example.com')</code> -
使用内置的
open()函数从本地文件获取 HTML 文档:<code>with open('example.html', 'r') as f: html_doc = f.read()</code>
-
-
创建 BeautifulSoup 对象:
-
使用
BeautifulSoup构造函数创建BeautifulSoup对象:<code>soup = BeautifulSoup(html_doc, 'html.parser')</code>
-
-
查找标签:
- 使用
find()或find_all()方法查找标签。find()返回第一个匹配标签,而find_all()返回所有匹配标签。 -
根据标签名称查找,例如:
<code>tags = soup.find_all('a')</code> -
根据属性查找,例如:
<code>tags = soup.find_all('a', {'href': 'https://example.com'})</code>
- 使用
提取标签内容:
一旦找到标签,就可以通过以下方式提取标签内容:
-
获取文本内容:
<code>text = tag.text</code>
-
获取 HTML 内容:
<code>html = tag.prettify()</code>
-
获取属性:
<code>attribute = tag.get('href')</code>
示例:
<code class="python">from bs4 import BeautifulSoup
import requests
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
tags = soup.find_all('a')
for tag in tags:
print(tag.text, tag.get('href'))</code>











