17

我正在尝试使用 urllib.request.urlopen() 打开一个网站(我在公司代理后面),但出现错误:

urllib.error.HTTPError: HTTP Error 407: Proxy Authentication Required

我可以在 urllib.request.getproxies() 中找到代理,但是如何指定要使用的用户名和密码呢?我在官方文档中找不到解决方案。

4

2 回答 2

29
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()
于 2012-08-01T16:12:22.647 回答
2

您可以使用您的凭据(用户名和密码)设置代理服务器身份验证,以使用请求连接到网站。这对我有用。要获取您的代理服务器名称:使用

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()
于 2020-01-20T02:34:40.817 回答