从弹出式Web链接下载zip文件

时间:2019-01-11 13:18:40

标签: python-3.x url zip

我有一个链接,当将其放入Web浏览器时,会弹出一个问题,询问是否打开或保存文件。我尝试了一些解决方案,但是没有按预期工作。

我已经尝试通过此处Download Returned Zip file from URL的帖子来实施解决方案。但是没有任何结果。我设法创建了zip文件,但是我遇到的问题是从URL到写入zip文件的过渡。

import requests, zipfile

path = "A:/"

url = "http://"+"www.sec.gov/dera/data/Public-EDGAR-log-file-data/2003 /Qtr4/log20031231.zip"
target_path = path + 'log20031231.zip'


results = requests.get(url)
zip = zipfile.ZipFile(path + 'log20031231_2.zip', "w")
insert = zipfile.ZipFile(results.content)
zip.write(results, compress_type=zipfile.ZIP_DEFLATED)
zip.close()

该代码创建zip,但是没有任何内容写入zip文件。控制台中的输出如下:

Traceback (most recent call last):
  File "A:/python project/testing/testing 3.py", line 17, in <module>
    insert = zipfile.ZipFile(results.content)
  File "C:\Users\Adrian\AppData\Local\Programs\Python\Python37\lib\zipfile.py", line 1222, in __init__
    self._RealGetContents()
  File "C:\Users\Adrian\AppData\Local\Programs\Python\Python37\lib\zipfile.py", line 1285, in _RealGetContents
    endrec = _EndRecData(fp)
  File "C:\Users\Adrian\AppData\Local\Programs\Python\Python37\lib\zipfile.py", line 259, in _EndRecData
    fpin.seek(0, 2)
AttributeError: 'bytes' object has no attribute 'seek'

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。这甚至不需要zip文件模块。它下载内容,然后将其放入存档。

import requests

url = "http://"+"www.sec.gov/dera/data/Public-EDGAR-log-file-data/2003/Qtr4/log20031231.zip"
open_url = requests.get(url)

with open('log20031231_2.zip', "wb") as code:
    code.write(open_url.content)