【问题标题】:Why request fails to download an excel file from web?为什么请求无法从 Web 下载 excel 文件?
【发布时间】:2021-12-06 11:44:46
【问题描述】:

url 链接是指向我正在尝试下载的 Web 文件(xlsb 文件)的直接链接。下面的代码可以正常工作,并且文件似乎是在路径中创建的,但是一旦我尝试打开它,就会在 excel 上弹出损坏的文件消息。响应状态为 400,因此这是一个错误请求。对此有何建议?

url = 'http://rigcount.bakerhughes.com/static-files/55ff50da-ac65-410d-924c-fe45b23db298'
file_name = r'local path with xlsb extension'


with open(file_name, "wb") as file:
    response = requests.request(method="GET", url=url)
    file.write(response.content) 

【问题讨论】:

  • 我正在努力将我想要的代码部分复制粘贴到代码编辑器中。我现在可能已经编辑了 5 次。复制粘贴代码有问题。
  • 只是为了以后编辑的一个注释,你不需要缩进任何行,也可以用```代码围栏换行。例如 ```python3 开头来表示语言。

标签: python excel file url request


【解决方案1】:

似乎对我有用。试试这个:

from requests import get

url = 'http://rigcount.bakerhughes.com/static-files/55ff50da-ac65-410d-924c-fe45b23db298'

# make HTTP request to fetch data
r = get(url)

# check if request is success
r.raise_for_status()

# write out byte content to file
with open('out.xlsb', 'wb') as out_file:
    out_file.write(r.content)

【讨论】:

  • 能打开xlsb文件看看内容吗?现在使用您的代码,此消息会出现在输出中:out.xlsb is not UTF-8 encode
  • 嗯,这很奇怪。是的,我可以正常打开它并使用 MS Excel 查看内容。
  • 您使用的是哪个 Python 版本?不确定是否重要,但我使用的是 3.9。
  • 我的路径中有错误。现在可以完美地与您的代码配合使用。谢谢!我需要深入了解为什么我发布的初始代码给了我错误。
  • 没问题,很高兴知道它有帮助!
猜你喜欢
  • 2013-01-18
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多