使用 Python 从 URL 下载 Excel 文件

问题描述 投票:0回答:1

Excel 文件的 URL 是这样的: https://www.gso.gov.vn/wp-content/uploads/2024/03/IIP-ENG.xlsx

我有这个代码:

from datetime import datetime, timedelta

url = 'https://www.gso.gov.vn/wp-content/uploads/' + datetime.strftime(datetime.now() - timedelta(30), '%y') +'/' + datetime.strftime(datetime.now() - timedelta(30), '%m') + '/IIP-ENG.xlsx'

import requests
resp = requests.get(url, verify=False)
output = open('IIP.xlsx', 'wb')
output.write(resp.content)
output.close()

我可以看到正在下载的文件,但无法在 Office Excel 中打开它。文件已损坏。

resp

我也无法使用此代码打开:

import pandas as pd
df = pd.read_excel(open('IIP.xlsx', 'rb'),sheet_name=0, engine='openpyxl')
print(df.head(5)) 

BadZipFile 错误。该文件不是 Zip 文件。

如何解决这个问题?

python web-scraping request openpyxl
1个回答
0
投票

问题在于年份格式,

'%y'
将给出24,您需要
'%Y'
表示2024

datetime.strftime(datetime.now() - timedelta(30), '%Y')
© www.soinside.com 2019 - 2024. All rights reserved.