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

如何让Tabula-py处理PDF时跳过无效URL错误并继续循环?

解决Tabula-py处理不存在PDF URL时的报错跳过问题

问题说明

通过规则生成日期格式的PDF URL,使用Tabula-py提取PDF表格,工作日运行正常,但遇到周末无PDF的URL时脚本报错,尝试使用try/except语句无效。

错误原因

原脚本中tabula.read_pdf()调用位于try块外部,当目标URL不存在时,该函数直接抛出异常,无法被后续的try/except捕获,导致脚本中断。

修正后的代码

将tabula.read_pdf()及后续表格处理逻辑全部放入try块中,确保所有可能抛出异常的操作都能被捕获并跳过:

import datetime
import pandas
import tabula

# 创建URL列表文件
with open('urls.txt', 'w') as df:
    start = datetime.datetime(2022, 11, 1)
    end = datetime.datetime(2022, 11, 11)
    delta = datetime.timedelta(days=1)
    pdf_path = 'https://www.irishprisons.ie/wp-content/uploads/documents_pdf/{date1:%d-%B-%Y}.pdf'

    while start < end:
        date1 = start
        url = pdf_path.format(date1=date1)
        df.write(f"{url}\n")  # 每行写入一个URL,便于后续查看
        
        # 尝试处理当前URL的PDF
        try:
            # 读取PDF表格,若URL无效则抛出异常
            dfs = tabula.read_pdf(url, pages='1', lattice=True, stream=True, pandas_options={'header': None})
            
            # 表格处理逻辑
            new_header = dfs[0].iloc[1]
            inmate_count = dfs[0].drop(labels=0, axis=0)
            inmate_count.columns = [new_header]
            inmate_count = inmate_count.dropna(how='all').reset_index(drop=True)
            inmate_count = inmate_count.drop(labels=[0], axis=0)
            inmate_count['url'] = url
            inmate_count.to_csv("first_table.csv", mode='a', header=False, index=False)
            print(inmate_count)
        except Exception as e:
            # 打印错误信息便于排查,也可注释掉
            print(f"处理URL {url} 时出错: {str(e)}")
            pass
        
        start += delta

print("Finished")

额外优化说明

  • 使用with open()上下文管理器自动关闭文件,避免资源泄漏
  • 写入URL时添加换行符\n,让每个URL单独占一行,提升可读性
  • 在except块中添加错误打印,方便排查具体是哪个URL出错及错误原因

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:05:24