【问题标题】:Python 3 - urllib, HTTP Error 407: Proxy Authentication RequiredPython 3 - urllib,HTTP 错误 407:需要代理身份验证
【发布时间】:2012-07-30 13:44:11
【问题描述】:

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

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

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

【问题讨论】:

标签: python authentication proxy urllib


【解决方案1】:

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

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()

【讨论】:

  • 如果您可以添加更多的 cmets 来解释代码如何解决 OP 的问题,那就太好了。
【解决方案2】:
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()

【讨论】:

  • 谢谢。如果不提供用户名和密码,有没有办法做到这一点?
  • 如果您担心在源代码中硬编码凭据(从而泄漏到 git 或其他 VCS 工件等),那么最好的方法是使用 configparser 之类的东西,或者YAML 或 JSON,将凭据存储在它们自己的单独文件中。从配置设置动态构建 ProxyHandler URL。这使您的来源可以被阅读,同时保持凭据的机密性。
  • 一个小提示:对我来说,他有“@url:port”的地方我实际上使用了机器名称“@machine:port”,而不是完整的 URL。
  • 我使用的是 Python 2.7,这看起来如何?我必须使用 urllib2 吗?
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 2016-09-05
  • 1970-01-01
相关资源
最近更新 更多