如何将代理身份验证传递给python请求模块 [英] How to pass proxy-authentication to python Requests module

查看:108
本文介绍了如何将代理身份验证传递给python请求模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用 request 模块执行对网站的获取/发布的现有python代码.

I'm working on existing python code that uses the request module to perform get/post towards a web site.

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

The python code also allow the use of proxies when a proxy is passed to the script otherwise no proxies are used.

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

My problem regards the use of proxies that requires authentication.

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 都会被拒绝,因为没有提供身份验证.

In the code above, if the proxy is configured each get is refused because no authentication is provided.

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

I found a solution that implies the use of HTTPProxyAuth.

这是我找到的解决方案:

This is the solution that I found:

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

My question is: is it possibile to set the proxy authorization globally instead of modify each s.get in the code? Because sometime the script could be used without proxy and sometimes with proxy.

提前谢谢!

最好的问候, 费德里科

Best Regards, Federico

推荐答案

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

I found the solution, about how to set proxy authentication globally:

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请求模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆