【问题标题】:Python 'requests' module to download an excel file from a download link which pops up a dialogue boxPython“请求”模块从弹出对话框的下载链接下载excel文件
【发布时间】:2019-12-12 04:33:38
【问题描述】:

我是一个新手,尝试使用 python 的请求模块从链接下载文件。 单击时,该链接将打开一个窗口以选择文件名和目录。 这是我尝试过的代码:

url = "http://dart.fss.or.kr/pdf/download/excel.do?lang=ko&rcp_no=20160516003174&dcm_no=5146351"
response = requests.get(url)
with open("test.xls", 'wb') as f:
    f.write(response.content)

虽然它生成 test.xls 文件,但它是空的,即使我可以手动从链接中保存一个 excel 文件。如何处理弹出下载窗口而不是直接提供文件的链接?当我点击链接时,如何检查所传递的 HTTP 消息(?)?

【问题讨论】:

  • 您的f.write(response.content) 是否在with open 代码块内缩进?
  • @Trollsors 谢谢你,我纠正了我在问题中的错误。

标签: python http download python-requests


【解决方案1】:

请求还期望像这样的 cookie、标头和参数:

import requests

cookies = {
    'PDFJSESSIONID': 'sOESblx1pDvLATuxG1GzATU71604r1Q9a74W0hbmzocJBzaqy1tDlpcM2Hd1VVMT.ZG1fcGRmL2ZpbGVyM19wZGZfbXMx',
    'WMONID': 'mOKYA_fvs-9',
}

headers = {
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'es-ES,es;q=0.9',
}

params = (
    ('lang', 'ko'),
    ('rcp_no', '20160516003174'),
    ('dcm_no', '514635'),
)

response = requests.get('http://dart.fss.or.kr/pdf/download/excel.do', headers=headers, params=params, cookies=cookies, verify=False)

with open("test.xls", 'wb') as f:
    f.write(response.content)

现在你有了完整数据的excel

提示:您可以从您的控制台谷歌浏览器(示例)访问完整的请求,然后在网络中检查它

【讨论】:

  • 谢谢你,乔瓦尼!我成功地使用你教我的东西下载了一个 excel 文件。经过几次试验,我发现它仍然适用于“response = requests.get('dart.fss.or.kr/pdf/download/excel.do', headers=headers, params=params)”(没有cookie)。在这里,更不用说“params”了,为什么“headers”在“requests.get”中很重要?为什么只使用我原来的url链接的一部分,也就是最多“xxx/excel.do”? (谷歌搜索告诉我,以“.do”结尾的 url 与“Java Servlet”相关,我不知道。)
  • 事实上,只有“User-Agent”元素的“header”可以正常工作。
  • 是的......即使你可以使用这个 curl 并转换为 python......只需输入 Google ....curl to python
猜你喜欢
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 2022-01-21
  • 1970-01-01
  • 2014-09-11
相关资源
最近更新 更多