【问题标题】:How to pass proxy-authentication to python Requests module如何将代理身份验证传递给 python 请求模块
【发布时间】:2019-02-02 05:33:56
【问题描述】:

我正在处理使用 request 模块执行获取/发布到网站的现有 python 代码。

python 代码还允许在将代理传递给脚本时使用代理,否则不使用代理。

我的问题与使用需要身份验证的代理有关。

proxy = user:password@ip:port
self.s = requests.Session()
if proxy != "":
      self.proxies = {
        "http": "http://" + proxy,
        "https": "https://" + proxy
      }
      self.s.proxies.update(proxies)

self.s.get('http://checkip.dyndns.org')

在上面的代码中,如果配置了代理,则每个 get 都会被拒绝,因为没有提供身份验证。

我找到了一个暗示使用 HTTPProxyAuth 的解决方案。

这是我找到的解决方案:

import requests
s = requests.Session()

proxies = {
  "http": "http://ip:port",
  "https": "https://ip:port"
}

auth = HTTPProxyAuth("user", "pwd")
ext_ip = s.get('http://checkip.dyndns.org', proxies=proxies, auth=auth)
print ext_ip.text

我的问题是:是否可以全局设置代理授权而不是修改代码中的每个 s.get?因为有时脚本可以在没有代理的情况下使用,有时也可以使用代理。

提前致谢!

最好的问候, 费德里科

【问题讨论】:

  • 您的会话对象需要代理详细信息,以便您可以使用 s.proxies=proxies
  • @NishantPatel 是的,但关于授权?我还需要指定代理的用户名和密码。

标签: python authentication proxy python-requests


【解决方案1】:

我找到了解决方案,关于如何全局设置代理身份验证:

import requests
import urllib2
import re
from requests.auth import HTTPProxyAuth

s = requests.Session()

proxies = {
  "http": "http://185.165.193.208:8000",
  "https": "https://185.165.193.208:8000"
}

auth = HTTPProxyAuth("gRRT7n", "NMu8g0")

s.proxies = proxies
s.auth = auth        # Set authorization parameters globally

ext_ip = s.get('http://checkip.dyndns.org')
print ext_ip.text

BR, 费德里科

【讨论】:

  • 你应该将此答案标记为问题的解决方案,如果它解决了它。
猜你喜欢
  • 2012-11-10
  • 1970-01-01
  • 2023-04-02
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多