【问题标题】:Problems with requests Python 3 retrieving an excel file from a WP site请求 Python 3 从 WP 站点检索 excel 文件的问题
【发布时间】:2021-05-17 18:45:43
【问题描述】:

这是我的问题,如果我键入,我正在尝试从 WP 网站下载 excel xlsx 文件

我在我的代码中分配给一个变量的网址,称为股票,直接在浏览器中,Firefox 完美下载。

我正在尝试使用 Python 执行此操作,因此我使用请求制作了一个脚本,然后使用 Pandas 进行处理和操作。

然而,即使文件似乎下载它返回一个错误,我尝试同时使用 open 和 with open,正如我在这里发现的类似问题上所建议的那样,但在我的情况下,它返回一个错误'ValueError: Seek of closed file ',我尝试了代码的几种变体,但没有结果,结果总是错误。

这是我的代码

import pandas as pd
import requests, os
import http.client

http.client.HTTPConnection._http_vsn = 10
http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'

# Url of the same link I used to manually fetch the file
stock = 'https://filmar.com/wp-content/uploads/2021/05/Apple-Lot-5-14-21.xlsx'

resp = requests.get(stock)  # passed the GET method to the http request with the URL

print("Downloading...") # This works

# When I try to retrieve the file it fails 
with open('Apple-Lot-5-14-21.xlsx', 'wb') as output:
    output.write(resp.content)
    
print('The file has been downloaded') # this is printed

# The error happens when I try to assign the file to the pd.read_excel method in Pandas
apple = pd.read_excel(output)

附录

输入@MattDMo提供的代码resp - object后,显然是权限问题什么的,因为分析响应对象,models.response返回404,未找到,所以要么是保护,要么是重定向这发生在服务器上,因此 requests 检索一个空文件。

【问题讨论】:

  • 您已将文件下载到内存中,但尚未将其保存到磁盘。

标签: python pandas python-requests


【解决方案1】:

您不能将output 传递给pd.read_excel(),因为当with 上下文管理器退出时,对文件(output) 的引用将被破坏。如果您真的不需要将 Excel 文件保存为其他任何内容,这里的一种选择是将resp.content 直接传递给read_excel()。或者,如果您希望 Excel 文件用于备份或其他目的,请创建一个文件名变量,如下所示:

xl_file = 'Apple-Lot-5-14-21.xlsx'

然后在您调用with open(... 时使用该变量在您调用read_excel() 时使用该变量,因为该函数可以接受文件名和类似文件的对象。

另外说明一下,我不确定您为什么要使用 http.client,因为据我所知,requests 没有考虑任何这些值。

【讨论】:

  • 感谢您的回复! @MattDMo,我已经使用 Pandas 工作了几个月,但大多数时候它们都是 csv 文件,对请求库和 read_excel() pandas 方法并不十分熟悉。我认为检索到的文件有问题,因为下载的文件具有不同的权重,而不是 15k,它更像是 162 字节,所以我试图弄清楚是否有一些丢失的参数,或者其他什么由于经验不足,我跳过了。顺便说一句,我使用 http.client 是因为我在这里读到了一个类似的案例,它使用了它,用于类型 http 1.0 reqs。
猜你喜欢
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
相关资源
最近更新 更多