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

如何用Python Requests+BeautifulSoup提取HTML中<br>分隔的指定数据

解决方案

完整代码示例

import requests
from bs4 import BeautifulSoup

# 示例目标HTML结构(可替换为你实际获取的HTML内容)
target_html = """
<div class="specs-section">
    <strong>Operating System</strong><br>Windows 10 Home Acer recommends Windows 10 Pro for business<br>
    <strong>Processor Manufacturer</strong><br>Intel®<br>
    <strong>_Internal Model_</strong><br>XYZ-789<br>
    <strong>Memory Type</strong><br>DDR4 SDRAM<br>
</div>
"""

# 若从网页抓取数据,替换为以下代码:
# response = requests.get("目标网页的URL")
# target_html = response.text

soup = BeautifulSoup(target_html, "html.parser")

head = []
value = []

# 遍历所有<strong>标签
for strong_tag in soup.find_all("strong"):
    strong_text = strong_tag.get_text(strip=True)
    # 筛选不带下划线的标签内容
    if "_" not in strong_text:
        head.append(strong_text)
        # 跳过<br>标签和空白节点,提取后续的有效文本值
        next_node = strong_tag.next_sibling
        while next_node and (next_node.name == "br" or next_node.strip() == ""):
            next_node = next_node.next_sibling
        if next_node:
            value.append(next_node.strip())

# 输出结果
print("head列表:", head)
print("value列表:", value)

# 若需组成键值对格式的列表
result_list = [{"key": h, "value": v} for h, v in zip(head, value)]
print("组合后的结果列表:", result_list)

关键说明

  • 筛选逻辑:通过检查<strong>标签文本是否包含下划线_,精准过滤出需要的表头内容。
  • 值提取技巧:利用next_sibling遍历节点,自动跳过<br>标签和无效空白文本,直接获取<br>后的关联值。
  • 空白处理:全程使用strip()清理文本前后的空格、换行符,避免无效空白影响结果。
  • 网页适配:如果数据来自在线网页,只需替换示例中的target_html为requests.get返回的响应文本即可,可额外添加try-except块处理请求异常。

内容的提问来源于stack exchange,提问作者Mandar Raut

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:45:10