【问题标题】:Python Won't Download URL-Based zip FilePython 不会下载基于 URL 的 zip 文件
【发布时间】:2019-11-25 22:23:40
【问题描述】:

所以我有一个从 Houzz 生成的 URL,如果我将该 URL 放入浏览器,下载 ZIP 就好了。

我正在尝试使用几种类型的选项下载该 zip,而我得到的是文件中包含 0 个数据。只是一个空文件

finalurl = 'https://theurltomyzip/thefile.zip'
import requests
import urllib
import urllib2
file_name = 'C:\\Users\\inventoryuser\\Downloads\\test.zip'
file_name2 = 'C:\\Users\\inventoryuser\\Downloads\\test2.zip'
file_name3 = 'C:\\Users\\inventoryuser\\Downloads\\test3.zip'

print "downloading with urllib"
urllib.urlretrieve(finalurl, file_name)

print "downloading with urllib2"
f = urllib2.urlopen(finalurl)
data = f.read()
with open(file_name2, "wb") as code:
    code.write(data)

print "downloading with requests"
r = requests.get(finalurl)
with open(file_name3, "wb") as code:
    code.write(r.content)

如前所述,这会产生 3 个完全空白的“zip”文件。

注意:如果您将“finalurl”的字符串值放入浏览器,它会立即下载 zip 文件。 (我也尝试过,在另一个迭代中但没有成功,“allow_redirects = True”)

【问题讨论】:

  • finalurl 是真正的 url,还是重定向?浏览器会自动跟随重定向,但您的代码示例不会。
  • 某些页面使用JavaScript 重定向或生成数据,但requests/urllib 无法运行JavaScript。您可能需要Selenium 来控制可以运行JavaScript 的真实网络浏览器。
  • 某些页面的系统受限更多,如果您没有正确的标题或 cookie,则它不会发送数据。您必须在 Chrome/Firefox 中使用 DevTool 来分析浏览器下载文件时发送的所有数据。
  • 该死的。 @furas 我试图将其作为使用 Selenium 绑定(我已设置)的替代方法;因为这似乎也阻止了我的下载。我想它一定是某种botmanager。
  • 如果你想使用reuqests,那么你应该先在浏览器中关闭JavaScript,然后在浏览器中测试url。如果没有 JavaScript 就无法工作,那么浏览器可能会看到一些有用的信息。如果它什么也没看到,那么您必须使用 JavaScript 运行浏览器并在 DevTools(选项卡“网络”)中查看 JavaScript 是否使用其他 url 来获取 zip 文件,然后您可以在代码中使用此 url。也许你甚至会在 HTML 中的某个地方找到这个 url——也许在 HTML 中的 JavaScript 中。

标签: python download python-requests


【解决方案1】:

试试这个:

import urllib.request

url = 'https://theurltomyzip/thefile.zip'

remote = urllib.request.urlopen(url)  # read remote file
data = remote.read()  # read from remote file
remote.close()  # close urllib request
local = open('download.zip', 'wb')  # write binary to local file
local.write(data)
local.close()  # close file

注意:我已经用 ftp://ftp.wwpdb.org/pub/pdb/data/structures/all/pdb/pdb106d.ent.gz 测试过

我觉得你的代码没问题,可能是网址有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多