gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:39:35 25 4
gpt4 key购买 nike

我正在开发现有的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com