You need to enable JavaScript to run this app. 如何在现有爬取脚本中将多类字段整合到单个pandas DataFrame中展示?
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有爬取脚本中将多类字段整合到单个pandas DataFrame中展示?

脚本修正与数据整合实现方案

原脚本存在的核心问题

  • 对BeautifulSoup返回的<tr>节点直接调用pandas的.iloc索引,属于类型不兼容错误,运行时会直接抛出属性异常
  • 没有设置统一的数据存储容器,逐行提取的字段无法归集汇总
  • 硬编码遍历20行的写法容易因页面实际行数变化触发索引越界

修正后可直接运行的实现代码

import pandas as pd
import requests
from bs4 import BeautifulSoup

# 初始化空列表存储所有爬取到的记录
all_records = []

# 遍历目标分页
for i in range(1, 3):  
    url = f"https://portal.mvp.bafin.de/database/DealingsInfo/sucheForm.do?meldepflichtigerName=&zeitraum=0&emittentName=&d-5010980-p={i}&zeitraumVon=&emittentIsin=&meldepflichtigerButton=Suche+Meldepflichtiger&zeitraumBis="
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html5lib")
    table = soup.find("table", {"class":"displaytag"})
    tbody = table.find("tbody")

    # 自动遍历表格下所有行,取消硬编码行数限制
    for tr in tbody.find_all("tr"):
        tds = tr.find_all("td")
        # 跳过单元格数量不足的异常行
        if len(tds) < 5:
            continue
        # 逐字段提取文本,自动清除多余空白字符
        record = {
            "name": tds[0].get_text(strip=True),
            "vorname": tds[1].get_text(strip=True),
            "titel": tds[2].get_text(strip=True),
            "position": tds[3].get_text(strip=True),
            "date": tds[4].get_text(strip=True)
        }
        all_records.append(record)

# 生成整合后的DataFrame并展示
df = pd.DataFrame(all_records)
print(df)

关键实现说明

  • 单元格文本提取使用get_text(strip=True)方法,可自动过滤前后多余的换行、空格,减少后续数据清洗工作量
  • 逐行遍历tbody下所有<tr>节点,替代固定循环20次的写法,可适配页面行数调整的场景,避免索引越界
  • 增加单元格数量校验逻辑,遇到跨列排版的异常行时直接跳过,不会中断整体爬取流程
  • 所有爬取记录以字典格式存入列表,直接传入pd.DataFrame()即可自动匹配对应列名,完成五类字段的整合展示,后续可直接基于DataFrame做筛选、导出等操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 18:15:05