python - 如何将代理身份验证传递给 python 请求模块

标签 python authentication proxy python-requests

我正在开发现有的 python 代码,该代码使用 request 模块对网站执行 get/post 操作。

当代理传递给脚本时,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?因为有时脚本可以在没有代理的情况下使用,有时可以在有代理的情况下使用。

提前致谢!

最诚挚的问候, 费德里科

最佳答案

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

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, 费德里科

关于python - 如何将代理身份验证传递给 python 请求模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52043378/

相关文章:

authentication - Glassfish JMS(平面文件)身份验证

java - 如何在 REST API 中获取登录用户 ID

android 到 django - 如何验证用户身份

javascript - Node.js http-proxy 流量监控

python - 使用代理扭曲 getpage

python - Pyhook:一起使用 KeyboardEvents 和 MouseEvents

python - 如何根据字典值只打印一定范围内的字典键值?

python - LNK1181 : cannot open input file 'm.lib'

Python 在断言后运行多个命令

java - PKIX 路径验证失败 : Path does not chain with any of the trust anchors using a proxy