gpt4 book ai didi

python - 无法使用 urllib2 下载整个文件

转载 作者:行者123 更新时间:2023-12-01 05:32:02 26 4
gpt4 key购买 nike

您好,我正在尝试从此 URL ( http://www.sicom.gov.co/precios/controller?accion=ExportToExcel ) 下载 Excel 文件,然后我需要使用 xlrd 解析它。

问题是,当我将该 Url 放在浏览器上时,我会得到一个或多或少 2MB 的 excel 文件,但是当我使用 urllib2、http2lib 甚至从命令行中的curl 下载该文件时,我只得到一个 4k 文件,显然解析那个不完整的文件惨遭失败。

奇怪的是,xlrd 似乎能够从下载的文件中读取正确的工作表名称,因此我猜测该文件是正确的,但它显然不完整。

这是我想要实现的一些示例代码

import urllib2
from xlrd import open_workbook

excel_url = 'http://www.sicom.gov.co/precios/controller?accion=ExportToExcel'

result = urllib2.urlopen(excel_url)
wb = open_workbook(file_contents=result.read())
response = ""
for s in wb.sheets():
response += 'Sheet:' + s.name + '<br>'
for row in range(s.nrows):
values = []
for col in range(s.ncols):
value = s.cell(row, col).value
if (value):
values.append(str(value) + " not empty")
else:
values.append("Value at " + col + ", " + row + " was empty")
response += str(values) + "<br>"

最佳答案

您必须先调用您的第一个网址。它似乎设置了一个cookie或类似的东西。然后调用第二个下载excel文件。对于此类工作,您应该更喜欢 http://docs.python-requests.org/en/latest/# ,因为它比标准库工具更容易使用,并且默认情况下它可以更好地处理特殊情况(例如 cookie)。

import requests

s = requests.Session()
s.get('http://www.sicom.gov.co/precios/controller?accion=Home&option=SEARCH_PRECE')
response = s.get('http://www.sicom.gov.co/precios/controller?accion=ExportToExcel')

with file('out.xls','wb') as f:
f.write(response.content)

关于python - 无法使用 urllib2 下载整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19987063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com