首页 > 编程问答 >BeautifulSoup:获取特定标签的标签文本

BeautifulSoup:获取特定标签的标签文本

时间:2024-07-30 15:03:12浏览次数:8  
标签:python web-scraping beautifulsoup

我想获取 HTML 页面上所有显示的文本,直到点击某个标签。例如,我想获取页面上所有显示的文本,直到点击 id 为“end_content”的标签为止。

有没有办法用 BeautifulSoup 来做到这一点? 这与 soup.get_text() 方法类似,只不过它会在遇到 id 为“end_content”的标签后停止获取文本。


可以使用 Beautiful Soup 来实现这一点,但是没有直接的方法可以在遇到特定标签后停止获取文本。

以下两种方法可以实现你的需求:

方法一: 使用 find_all() 和循环

  1. 使用 soup.find_all(text=True) 获取所有文本节点。
  2. 遍历文本节点,如果遇到 id end_content 的标签,则停止遍历。
from bs4 import BeautifulSoup

html = """
<html>
<body>
  <p> 这是一些文本。</p>
  <div id="end_content"> 停止获取文本</div>
  <p> 这段文本不应该被获取。</p>
</body>
</html>
"""

soup = BeautifulSoup(html, 'html.parser')

text_content = ""
for element in soup.find_all(text=True):
  if element.find_parent(id="end_content"):
    break
  text_content += element.strip() + " "

print(text_content)

方法二: 使用 extract() 方法

  1. 找到 id end_content 的标签。
  2. 使用 extract() 方法移除该标签及其后面的所有内容。
  3. 使用 soup.get_text() 获取剩余内容的文本。
from bs4 import BeautifulSoup

html = """
<html>
<body>
  <p> 这是一些文本。</p>
  <div id="end_content"> 停止获取文本</div>
  <p> 这段文本不应该被获取。</p>
</body>
</html>
"""

soup = BeautifulSoup(html, 'html.parser')

end_tag = soup.find(id="end_content")

if end_tag:
  # 移除 end_tag 及其后面的所有内容
  end_tag.find_parent().extract() 

text_content = soup.get_text(strip=True)
print(text_content)

两种方法都可以实现你的需求,选择哪种方法取决于你的具体情况和个人偏好.

标签:python,web-scraping,beautifulsoup
From: 50578090

相关文章

  • 如何使用 python 在 influxdb 中创建组织和存储桶
    如何使用python在influxdb中创建组织和存储桶?我有一个python脚本,用于在influxdb中创建组织和存储桶,但它无法工作并返回未经授权的响应任何人可以使用influxdbapi帮助我解决这个问题吗?HTTPresponsebody:{"code":"unauthorized","message":"write:org......
  • Python - File opening modes and buffering
    'r'-readmode(default)'w'-writemode'a'-appendmode'x'-exclusivecreationWeknowthatthemode'r'opensanexistingfileforreadingonly;thefileshouldalreadyexist.Ifyouopenafilein......
  • 如何使用 Python 对图像中的掩模部分进行聚类?
    我需要以这样的方式拆分蒙版:如果蒙版内存在不一致,则会将其分开。例如,如果我在一只猫上画一个面具,我希望宽的部分(身体)是一个面具,窄的部分(尾巴)是另一个面具。目前,我有一个连续的面具,其中包括两者猫的身体和尾巴。我想将其分成两个不同的面具。如何使用Python实现此目的?原......
  • 如何在 python 中为具有不同类型作为值的字典添加类型声明
    我有一个字典如下my_dict={"key_1":"value_1","key_2":{"key_1":True,"key_2":1200}"key_3":True,}并且在我的类中@dataclassclassTestClass:my_dict:typing......
  • Python TypedDict:继承另一个TypedDict时的函数语法
    给定这种类型:classTPerson(TypedDict):name:straddress:str我想要另一个TypedDict继承前一个,例如:classTDealer(TPerson):db-id:intpolice_record:strarrested_now:boolclassTConsumer(TPerson):db-id:intpreferred_product:......
  • 如何让 python 类型在需要父类时将子类识别为有效类型?
    这是我需要做的一个最小示例:fromtypingimportCallable,AnyclassData:passclassSpecificData(Data):passclassEvent:passclassSpecificEvent(Event):passdefdetect_specific_event(data:SpecificData,other_info:str)->Specif......
  • 使用 Python + Beautiful Soup 抓取任何包含 5 个数字的字符串
    我住在德国,那里的邮政编码在大多数情况下都是5位数字。53525。我真的很想使用beautifulSoup从网站中提取该信息。我是Python/BeautifulSoup的新手,我不知道如何将“查找连续的每5个数字+“空格””翻译成Python语言。importrequestsimporturllib.re......
  • 如何测试 python 类型协议是另一个协议的子类?
    该问题的明显解决方案是使用issubclass,但这会引发TypeError(使用Python3.6.7),例如>>>fromtyping_extensionsimportProtocol>>>classProtoSubclass(Protocol):...pass...>>>issubclass(ProtoSubclass,Protocol)Traceback(mos......
  • Python:指定与继承一起使用的类方法的返回类型
    我一直在尝试了解如何在Python中指定类方法的返回类型,以便即使对于子类也能正确解释它(例如在我的Sphinx文档中)。假设我有:classParent:@classmethoddefa_class_method(cls)->'Parent':returncls()classChild(Parent):pass什么如......
  • python使用SMTP功能发送邮件
    网页格式发送for_email.html<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><style>h1{color:brown;}p{margin:5px;color:purple......