urllib.request.urlretrieve与代理?

cap*_*alg 11 urllib python-3.x

不知怎的,我不能通过代理服务器下载文件,我不知道我做错了什么.我只是暂停了.有什么建议?

import urllib.request

urllib.request.ProxyHandler({"http" : "myproxy:123"})
urllib.request.urlretrieve("http://myfile", "file.file")
Run Code Online (Sandbox Code Playgroud)

dor*_*vak 25

您需要使用您的代理对象,而不仅仅是实例化它(您创建了一个对象,但没有将它分配给变量,因此无法使用它).尝试使用此模式:

#create the object, assign it to a variable
proxy = urllib.request.ProxyHandler({'http': '127.0.0.1'})
# construct a new opener using your proxy settings
opener = urllib.request.build_opener(proxy)
# install the openen on the module-level
urllib.request.install_opener(opener)
# make a request
urllib.request.urlretrieve('http://www.google.com')
Run Code Online (Sandbox Code Playgroud)

或者,如果您不需要依赖std-lib,请使用请求(此代码来自官方文档):

import requests

proxies = {"http": "http://10.10.1.10:3128",
           "https": "http://10.10.1.10:1080"}

requests.get("http://example.org", proxies=proxies)
Run Code Online (Sandbox Code Playgroud)

  • @arbel在Python3中,确实如此.[来源](https://docs.python.org/3/library/urllib.request.html) (2认同)