python爬虫抓取span内容的方法:使用beautifulsoup库解析html文档通过css选择器或正则表达式定位span元素及其内容

Python 爬虫如何抓取 Span 中的内容
方法:
使用 Python 的 BeautifulSoup 库解析 HTML 文档,并通过 CSS 选择器或正则表达式定位 Span 元素及其内容:
步骤:
立即学习“Python免费学习笔记(深入)”;
- 导入 BeautifulSoup 库:
<code class="python">from bs4 import BeautifulSoup</code>
- 解析 HTML 文档:
<code class="python">html_doc = """
<html>
<body>
<span id="my-span">This is a span.</span>
</body>
</html></code>- 使用 CSS 选择器定位 Span 元素:
<code class="python">soup = BeautifulSoup(html_doc, 'html.parser')
span_element = soup.select_one('#my-span')</code>- 获取 Span 中的内容:
- 使用 text 属性获取纯文本:
<code class="python">span_text = span_element.text</code>
- 使用 html 属性获取 HTML 内容:
<code class="python">span_html = span_element.html</code>
- 使用正则表达式定位 Span 元素:
<code class="python">import re pattern = '<span id="my-span">(.+?)</span>' matches = re.findall(pattern, html_doc) span_text = matches[0]</code>











