无法以编程方式下载xls文件



我可以通过在浏览器中粘贴url手动下载此文件:https://www.aaii.com/files/surveys/sentiment.xls

然而,当我尝试以编程的方式做到这一点时,我没有运气。根据我使用的库(requests、urlib、urlib3(,错误要么是403,要么只是返回一些文本为"request successful"的html。奇怪的是,它工作了几次——我能够下载excel文件。那么它将在不改变任何编码的情况下停止。这是非常奇怪和零星的。

想知道是否有人可以尝试这个代码,看看他们是否有同样的问题,或者可以看看是否有什么我做得不正确的

UPDATE :似乎如果我等待一段时间,然后再次尝试运行代码,它就会工作。就好像服务器在给定的时间段内可能对请求数量有限制一样。如果有人能看到这种情况是否也发生在身上,那就太好了

import pandas as pd
import requests
url="https://www.aaii.com/files/surveys/sentiment.xls"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
'Accept': '.xls,.xlsx,application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.9',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'DNT': '1'
}
resp = requests.get(url=url, headers=headers)
data = resp.content
print(data)
with open('test.xls', 'wb') as output:
output.write(data)
df=pd.read_excel(data)
# df=pd.read_excel(url, header=headers)

您的代码似乎对我有效。然而,当我第二次运行它时,我收到了以下错误消息:

IOSub数据速率超出。Jupyter服务器将暂时停止将输出发送到客户端以避免其崩溃。若要更改这个限制,设置配置变量CCD_ 1。

当前值:ServerApp.ioub_data_rate_limit=1000000.00(字节/秒(ServerApp.rate_limit_window=3.0(秒(

您要下载的服务器似乎设置了date_rate_limit

使用以下命令从外壳启动笔记本:
jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
为我解决了这个问题。

最新更新