【问题标题】:Getting http error 400 urllib2 when trying to download a file尝试下载文件时出现 http 错误 400 urllib2
【发布时间】:2016-02-22 04:52:42
【问题描述】:

事情就是这样,我正在做一个从不同站点下载文件的脚本。问题是我无法弄清楚为什么它会抛出这个错误,而如果我在浏览器上放置相同的 url,它会让我下载文件。还有其他可以正常工作的网址。所以...这是代码:

import os
from bs4 import BeautifulSoup
import time
import urllib2

f = urllib2.Request(url)
f.add_header('User-Agent', 'Mozilla/5.0 Windows NT 6.3; WOW64; rv:34.0')
request = urllib2.urlopen(f)
data = request.read()
soup = BeautifulSoup(data, 'html.parser')
p_name = soup.find('h2', id="searchResults").contents[0]
if not os.path.exists(p_name):
  os.makedirs(p_name)
for a in soup.find_all('a', href="#register"):
    f = a["data-durl"]
#Following two lines just prepares file name
    n = len(f.split("/"))
    n_file = f.split("/")[n-1]
    path_file = p_name+"\\"+n_file
    if os.path.isfile(path_file):
        print "Firmware already downloaded. skipping it"
    else:
        print "Downloading "+ path_file
        link = urllib2.urlopen(f)
        datos = link.read()
#print "[+] Downloading firmware %s" % n_file
#n_archivo = "Archivo"+str(b)+".zip"
        with open(path_file, "wb") as code:
           code.write(datos)
    time.sleep(2) 

此网址无法与此脚本一起使用:Non working url 但是这个工作正常working url

希望你能帮助我。

编辑:我添加了为此使用的库。 和堆栈跟踪 我发现了错误!!问题是它尝试下载的文件名上有空格。使用 f.replace(" ","%20") 应该可以正常工作:)

【问题讨论】:

  • 两个 URL 对我来说都很好。你从哪里得到错误?请发布完整的堆栈跟踪。

标签: python beautifulsoup urllib2


【解决方案1】:

您需要将文件名中的空格转换为空格的 URL 编码:%20。为此,您可以使用str.replace() 在这两行之间添加一行:

print "Downloading "+ path_file
f = f.replace(' ', '%20')
link = urllib2.urlopen(f)

这将从网址下载:

http://www.downloads.netgear.com/files/GDC/ME101/ME101%20Software%20Utility%20Version%202.0.zip

而不是来自

http://www.downloads.netgear.com/files/GDC/ME101/ME101 Software Utility Version 2.0.zip

这是无效的,因为它包含空格。

此 URL 在您的浏览器中仍然有效,因为当您输入带有空格的 URL 时,您的浏览器会自动将它们转换为 %20

【讨论】:

  • 没问题!狩猎愉快!
猜你喜欢
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-13
  • 2011-07-12
  • 1970-01-01
相关资源
最近更新 更多