You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python和BS提取两个指定关键词之间的所有文本?

使用Python和BeautifulSoup提取指定关键词间的文本

场景1:纯文本关键词作为边界

如果提取边界是普通文本(比如示例中的blabla和blibli),可以结合字符串定位和BeautifulSoup解析实现:

from bs4 import BeautifulSoup

# 示例HTML内容
html = "blabla <strong>text i need</strong> blibli"
soup = BeautifulSoup(html, "html.parser")

# 定义起始、结束关键词
start_key = "blabla"
end_key = "blibli"

# 把HTML转为字符串,定位边界位置
full_html_str = str(soup)
start_pos = full_html_str.find(start_key) + len(start_key)
end_pos = full_html_str.find(end_key)

# 提取中间内容,按需处理
middle_content = full_html_str[start_pos:end_pos].strip()
# 若需要纯文本,重新解析后提取文本
extracted_text = BeautifulSoup(middle_content, "html.parser").get_text(strip=True)

print(extracted_text)  # 输出: text i need

场景2:HTML标签作为边界

如果边界是特定HTML标签(比如要提取<strong>标签相关的区间内容),可以结合标签定位和字符串处理:

from bs4 import BeautifulSoup

html = "blabla <strong>text i need</strong> blibli"
soup = BeautifulSoup(html, "html.parser")

# 找到目标标签
target_tag = soup.find("strong")
full_html_str = str(soup)

# 提取"blabla"到标签结束之间的内容
start_pos = full_html_str.find("blabla") + len("blabla")
end_pos = full_html_str.find("</strong>") + len("</strong>")
middle_content = full_html_str[start_pos:end_pos].strip()

print(middle_content)  # 输出: <strong>text i need</strong>

多匹配场景处理

如果页面中存在多个重复的关键词边界,可通过循环迭代查找位置:

from bs4 import BeautifulSoup

html = "blabla <strong>text1</strong> blibli blabla <strong>text2</strong> blibli"
soup = BeautifulSoup(html, "html.parser")
start_key = "blabla"
end_key = "blibli"
full_html_str = str(soup)

current_pos = 0
while True:
    start_pos = full_html_str.find(start_key, current_pos)
    if start_pos == -1:
        break
    start_pos += len(start_key)
    end_pos = full_html_str.find(end_key, start_pos)
    if end_pos == -1:
        break
    content = full_html_str[start_pos:end_pos].strip()
    print(BeautifulSoup(content, "html.parser").get_text(strip=True))
    current_pos = end_pos + len(end_key)

# 输出:
# text1
# text2

内容的提问来源于stack exchange,提问作者steve figueras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:15:21