
在进行网页数据抓取时,beautifulsoup是一个功能强大且易于使用的python库,它能够从html或xml文件中提取数据。与scrapy等框架中基于xpath的选择器不同,beautifulsoup提供了更pythonic的api来遍历解析树。开始使用beautifulsoup的第一步是将html内容解析成一个可操作的beautifulsoup对象。
from bs4 import BeautifulSoup
# 示例HTML内容
html_doc = """
<div class="col-12 col-md-8">
<article class="article-main">
<header class="article-header">
<h1 class="article-title" style="font-size: 28px !important; font-family: sans-serif !important;">Presentation: Govt pushes CCS/CCUS development in RI upstream sector</h1>
<div class="article-meta">
<span class="meta-posted">
Monday, August 1 2022 - 04:27PM WIB </span>
</div>
</header>
</article>
</div>
"""
# 创建BeautifulSoup对象
soup = BeautifulSoup(html_doc, 'html.parser')为了准确地提取所需信息,首先需要理解目标HTML的结构。在上述示例HTML中,我们希望提取文章的标题和发布日期。
<h1 class="article-title">...</h1>
<span class="meta-posted">...</span>
我们的目标是获取这些标签内部的纯文本内容,而不是包含HTML标签的完整字符串。
BeautifulSoup提供了多种方法来定位HTML元素,其中findAll()(或其别名find_all())是最常用的之一。它用于查找所有符合条件的标签,并返回一个列表。
findAll()方法的基本用法是:soup.findAll(name, attrs, recursive, text, limit, **kwargs)。 在这里,我们主要关注name(标签名)和attrs(属性字典)。
定位文章标题: 标题位于<h1>标签中,且其class属性为article-title。
titles = soup.findAll('h1', attrs={'class':'article-title'})
# 此时 titles 是一个列表,包含所有匹配的 <h1> 标签对象
# 例如:[<h1 class="article-title" style="...">Presentation: Govt pushes CCS/CCUS development in RI upstream sector</h1>]定位发布日期: 日期位于<span>标签中,且其class属性为meta-posted。
dates = soup.findAll('span', attrs={'class':'meta-posted'})
# 此时 dates 也是一个列表,包含所有匹配的 <span> 标签对象
# 例如:[<span class="meta-posted">
# Monday, August 1 2022 - 04:27PM WIB </span>]需要注意的是,findAll()返回的是一个BeautifulSoup标签对象的列表。直接打印这些对象会显示包含HTML标签的完整字符串。
立即学习“前端免费学习笔记(深入)”;
为了从定位到的标签对象中获取纯文本内容,BeautifulSoup提供了get_text()方法。这个方法会移除标签本身,只返回其内部的文本。
我们可以遍历findAll()返回的列表,并对每个标签对象调用get_text()方法。
提取文章标题文本:
for title_tag in titles:
article_title_text = title_tag.get_text()
print(f"文章标题: {article_title_text}")提取发布日期文本:
for date_tag in dates:
published_date_text = date_tag.get_text()
print(f"发布日期: {published_date_text}")通过这种方式,我们就能获得干净、不含HTML标签的纯文本数据。
以下是将上述步骤整合到一起的完整代码示例:
from bs4 import BeautifulSoup
# 示例HTML内容
html_doc = """
<div class="col-12 col-md-8">
<article class="article-main">
<header class="article-header">
<h1 class="article-title" style="font-size: 28px !important; font-family: sans-serif !important;">Presentation: Govt pushes CCS/CCUS development in RI upstream sector</h1>
<div class="article-meta">
<span class="meta-posted">
Monday, August 1 2022 - 04:27PM WIB </span>
</div>
</header>
</article>
</div>
"""
# 创建BeautifulSoup对象
soup = BeautifulSoup(html_doc, 'html.parser')
# 提取文章标题
print("--- 提取文章标题 ---")
titles = soup.findAll('h1', attrs={'class':'article-title'})
for title_tag in titles:
print(title_tag.get_text())
# 提取发布日期
print("\n--- 提取发布日期 ---")
dates = soup.findAll('span', attrs={'class':'meta-posted'})
for date_tag in dates:
print(date_tag.get_text())运行上述代码,将得到以下输出:
--- 提取文章标题 ---
Presentation: Govt pushes CCS/CCUS development in RI upstream sector
--- 提取发布日期 ---
Monday, August 1 2022 - 04:27PM WIB find()与findAll()的选择:
处理空白字符:get_text(strip=True) 在上面的日期提取结果中,可以看到日期文本前后存在多余的空白字符。为了清理这些空白,可以在调用get_text()时传入strip=True参数。
for date_tag in dates:
published_date_text = date_tag.get_text(strip=True)
print(f"发布日期 (清理后): {published_date_text}")这将输出:发布日期 (清理后): Monday, August 1 2022 - 04:27PM WIB,使得数据更加整洁。
处理元素不存在的情况: 如果使用find()方法且目标元素不存在,它将返回None。在尝试对None对象调用方法(如get_text())时,会引发AttributeError
以上就是使用BeautifulSoup精准提取HTML元素文本内容的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号