我正在尝试使用urllib.request.urlopen()打开一个网站(我在公司代理服务器后面),但我收到错误:
urllib.error.HTTPError: HTTP Error 407: Proxy Authentication Required
我可以在urllib.request.getproxies()中找到代理,但是如何指定用于它的用户名和密码?我在官方文档中找不到解决方案。
答案 0 :(得分:23)
import urllib.request as req
proxy = req.ProxyHandler({'http': r'http://username:password@url:port'})
auth = req.HTTPBasicAuthHandler()
opener = req.build_opener(proxy, auth, req.HTTPHandler)
req.install_opener(opener)
conn = req.urlopen('http://google.com')
return_str = conn.read()
答案 1 :(得分:0)
您可以使用您的凭据(用户名和密码)设置代理服务器身份验证,以使用请求连接到网站。这对我有用。要获取代理服务器名称:使用
import urllib.request as req
import os
#get your proxy server url details using below command
req.getproxies()
#user your credentials and url to authenticate
os.environ['http_proxy'] = "http://username:pwd@url:80"
os.environ['https_proxy'] = "http://username:pwd@url:80"
#replace username, pwd and url with your credentials.
conn = req.urlopen('https://Google.com')
return_str = conn.read()