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

如何将Grobid解析PDF的curl命令转换为Python requests代码?

把Grobid的curl请求转成Python requests代码

没问题,我帮你把这段curl命令转换成Python的requests实现,核心就是模拟表单上传文件的操作,和你用curl --form的逻辑完全一致。

先回顾下你的原curl命令:

curl -v --form input=@example.pdf localhost:8070/api/processHeaderDocument

这里的--form input=@example.pdf是告诉curl要上传名为input的文件(也就是example.pdf)到指定的API端点。对应到requests里,我们需要用files参数来实现这个表单上传。

完整的Python代码示例

import requests

# 配置Grobid服务器地址和API端点
GROBID_BASE_URL = 'http://localhost:8070'
API_ENDPOINT = '/api/processHeaderDocument'
full_api_url = f"{GROBID_BASE_URL}{API_ENDPOINT}"

# 你要解析的PDF文件路径
target_pdf = 'example.pdf'

try:
    # 用with语句安全打开文件,自动管理资源
    with open(target_pdf, 'rb') as pdf_file:
        # 构造表单数据:字段名'input'必须和Grobid API要求的一致
        upload_data = {'input': pdf_file}
        # 发送POST请求
        response = requests.post(full_api_url, files=upload_data)
        
        # 检查请求是否成功(如果返回4xx/5xx状态码会抛出异常)
        response.raise_for_status()
        
        # 打印解析后的XML结果
        print("解析结果:")
        print(response.text)
        
        # 也可以把结果保存到本地文件
        with open('parsed_header.xml', 'w', encoding='utf-8') as output_file:
            output_file.write(response.text)
            print(f"结果已保存到 parsed_header.xml")
            
except FileNotFoundError:
    print(f"错误:找不到文件 {target_pdf},请检查文件路径是否正确")
except requests.exceptions.RequestException as e:
    print(f"请求失败:{str(e)},请确认Grobid服务器是否正常运行在8070端口")

关键细节说明

  • 文件上传的字段名:'input'这个字段名必须和Grobid API的要求一致,否则服务器无法识别上传的文件
  • 二进制模式打开文件:用'rb'模式打开PDF文件,因为文件上传需要传递二进制数据
  • 错误处理:代码里加了基础的异常捕获,比如文件找不到、请求失败的情况,方便你排查问题
  • 模拟curl的-v参数:如果需要查看详细的请求日志(像curl -v那样),可以在代码开头加上这段日志配置:
import logging
import http.client

# 开启requests的调试日志,输出类似curl -v的详细信息
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

最后别忘了确保你的Grobid服务器已经通过./gradlew run启动,并且确实运行在8070端口哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:49:56