Python不会下载基于url的zip-Fi

2024-06-30 15:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个从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\ u redirects=True”)


Tags: 文件importdownloadswithcodeurllib2urllibzip
1条回答
网友
1楼 · 发布于 2024-06-30 15:15:37

试试这个:

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测试过了

我认为你的代码是好的,也许有一个问题的网址。你知道吗

相关问题 更多 >