【问题标题】:How to Download All Zip Files From a Website Using Python如何使用 Python 从网站下载所有 Zip 文件
【发布时间】:2018-01-03 11:26:24
【问题描述】:

我正在尝试从以下位置下载所有压缩文件:https://www.google.com/googlebooks/uspto-patents-grants-text.html 网页。

完全披露,我不是专业的编码员,所以如果我犯了一些愚蠢的错误,请原谅我。

这是我的代码:

from bs4 import BeautifulSoup            
import requests

url = "https://www.google.com/googlebooks/uspto-patents-grants-text.html"
html = requests.get(url)
soup = BeautifulSoup(html.text, "html.parser")

for link in soup.find_all('a', href=True):
    href = link['href']

    if any(href.endswith(x) for x in ['.zip']):
    #if any(href.endswith('.zip')):
        print("Downloading '{}'".format(href))
        remote_file = requests.get(url + href)

        with open(href, 'wb') as f:
            for chunk in remote_file.iter_content(chunk_size=1024): 
                if chunk: 
                    f.write(chunk)  

我在运行代码时遇到的错误是: 文件“C:/Users/#USER#/#FILEPATH#/Python/patentzipscraper2.py”,第 16 行,在 使用 open(href, 'wb') 作为 f: OSError:[Errno 22] 无效参数:http://storage.googleapis.com/patents/grant_full_text/2015/ipg150106.zip'

但是,当我在浏览器中输入该地址时,我可以下载压缩文件。我猜这与压缩文件的格式有关,我不一定能直接下载/打开它们,但我不确定是什么。我基于此的代码是下载可以直接下载的文件(如 .txt)

任何有关如何下载这些 zip 的帮助将不胜感激。

【问题讨论】:

  • 您要下载 1976-.... 的所有数据?
  • 您正在尝试创建一个名为 'python 'http://storage.googleapis.com/patents/grant_full_text/2015/ipg150106.zip' 的写入文件。大概open 不喜欢这个名字。
  • 另一个奇怪的地方:remote_file = requests.get(url + href),但url + href 将解析为"https://www.google.com/googlebooks/uspto-patents-grants-text.htmlhttp://storage.googleapis.com/patents/grant_full_text/2015/‌​ipg150106.zip"。不应该是remote_file = requests.get(href)
  • 也许with open(os.path.basename(href), 'wb') as f: 这样你就写信给'ipg150106.zip'
  • 嗨,我已经尝试了这些更改中的每一个,但我仍然收到相同的错误(除了当我使用 os.path.basename 时,然后我收到一个错误消息:with open(os .path.basename(href), 'wb') as f: NameError: name 'os' is not defined 我应该以不同的方式写入文件吗?

标签: python python-3.x beautifulsoup zip


【解决方案1】:

在您的代码中实现类似:

import urllib

archive = urllib.request.URLopener()
archive.retrieve("http://yoursite.com/file.zip", "file.zip")

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多