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

如何用BeautifulSoup从HTML表格中提取目标<td>元素内容?

解决DNB页面表格内容提取问题

问题分析

原代码直接遍历页面所有<tr>标签,会包含大量无关行,且未准确区分每行内的多个<td>,导致无法精准获取目标元数据。

修正方案

先定位到存放目标信息的具体元数据表格,再遍历表格内的行,提取每行的字段名和对应内容:

import requests
from bs4 import BeautifulSoup

def getDescriptionDNB():
    # 目标页面URL
    url = 'https://portal.dnb.de/opac.htm?method=simpleSearch&cqlMode=true&query=idn%3D1173921214'
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    
    # 验证搜索结果为单条记录
    amount_text = soup.find(class_="amount").text.strip()
    if amount_text == "Treffer 1 von 1":
        # 定位右侧元数据表格(通过类名精准匹配)
        metadata_table = soup.find("table", class_="table table-striped table-condensed")
        if metadata_table:
            # 遍历表格每行,提取字段与内容
            for row in metadata_table.find_all("tr"):
                tds = row.find_all("td")
                if len(tds) == 2:
                    field = tds[0].text.strip()
                    value = tds[1].text.strip()
                    print(f"{field}: {value}")
        else:
            print("未找到目标元数据表格")
    else:
        print("搜索结果数量不符合预期")

# 调用函数
getDescriptionDNB()

额外优化(提升稳定性)

如果页面结构调整,可通过父容器定位表格,避免其他表格干扰:

# 先定位右侧内容容器
right_container = soup.find("div", class_="col-sm-9 col-md-8")
if right_container:
    metadata_table = right_container.find("table", class_="table table-striped table-condensed")

内容的提问来源于stack exchange,提问作者Benedikt Faude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 01:27:29