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

Python循环爬取多URL表格仅获最后表数据问题求助

问题分析与修复方案

核心问题

你的代码里**try...except块位于URL遍历循环的外部**,这意味着循环跑完所有URL后,Tableau_groupe变量只保留了最后一个URL对应的表格数据,后续的行遍历逻辑只会处理这最后一个表格,最终只收集到最后一个页面的10行数据。

另外还有两个小问题:

  • 多余的b=0声明,for b in BASE_URL会直接遍历列表元素,不需要提前赋值
  • 宽泛的except: pass会隐藏所有异常,比如某个页面请求失败、找不到表格时,你无法得知问题出在哪里

修正后的代码

import pandas as pd
from bs4 import BeautifulSoup
import requests

# URL列表
BASE_URL = [
    'https://datan.fr/groupes/legislature-16/re',
    'https://datan.fr/groupes/legislature-16/rn',
    'https://datan.fr/groupes/legislature-16/lfi-nupes',
    'https://datan.fr/groupes/legislature-16/lr',
    'https://datan.fr/groupes/legislature-16/dem',
    'https://datan.fr/groupes/legislature-16/soc',
    'https://datan.fr/groupes/legislature-16/hor',
    'https://datan.fr/groupes/legislature-16/ecolo',
    'https://datan.fr/groupes/legislature-16/gdr-nupes',
    'https://datan.fr/groupes/legislature-16/liot',
]

Tous_les_groupes = []

# 遍历每个URL,在循环内部处理表格数据
for url in BASE_URL:
    try:
        # 请求页面
        html = requests.get(url).text
        soup = BeautifulSoup(html, "html.parser")
        # 定位表格
        Tableau_groupe = soup.find('table', {"class": "table"})
        
        # 遍历表格行
        for row in Tableau_groupe.find_all('tr'):
            cols = row.find_all('td')
            if len(cols) == 4:
                Tous_les_groupes.append((
                    url, 
                    cols[0].text.strip(), 
                    cols[1].text.strip(), 
                    cols[2].text.strip(), 
                    cols[3].text.strip()
                ))
    except Exception as e:
        # 打印异常信息,方便调试哪个URL出了问题
        print(f"处理URL {url}时出错: {str(e)}")
        continue

# 直接用列表生成DataFrame,无需转numpy数组
df = pd.DataFrame(
    Tous_les_groupes,
    columns=['url','G', 'Tx', 'note', 'Number']
)

# 导出CSV
df.to_csv('output.csv', index=False)

关键修改说明

  1. 将表格处理的try...except逻辑移到URL循环内部,确保每个URL的表格都被遍历并收集数据
  2. 替换变量名b为url,更具可读性
  3. 保留异常捕获但添加错误打印,方便定位哪个页面出问题
  4. 直接通过列表创建DataFrame,去掉不必要的numpy数组转换
  5. 导出CSV时添加index=False,避免生成多余的索引列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:18:22