如何为请求会话对象设置单个代理?

2024-04-19 16:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python请求包发送http请求。我想向请求会话对象添加一个代理。例如

session = requests.Session()
session.proxies = {...} # Here I want to add a single proxy

目前,我正在一堆代理之间循环,每次迭代时都会生成一个新会话。我只想为每个迭代设置一个代理。

我在文档中看到的唯一示例是:

proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

我试过这么做,但没用。这是我的脚本代码:

# eg. line = 59.43.102.33:80
r = s.get('http://icanhazip.com', proxies={'http': 'http://' + line})

但我有个错误:

requests.packages.urllib3.exceptions.LocationParseError: Failed to parse 59.43.102.33:80

如何在会话对象上设置单个代理?


Tags: to对象addhttp代理getheresession
3条回答

除了@neowu'答案,如果您想为会话对象的生存期设置代理,还可以执行以下操作-

import requests
proxies = {'http': 'http://10.11.4.254:3128'}
s = requests.session()
s.proxies.update(proxies)
s.get("http://www.example.com")   # Here the proxies will also be automatically used because we have attached those to the session object, so no need to pass separately in each call

事实上,你是对的,但你必须确保你对“线”的定义,我试过了,没关系:

>>> import requests
>>> s = requests.Session()
>>> s.get("http://www.baidu.com", proxies={'http': 'http://10.11.4.254:3128'})
<Response [200]>

你是否定义了像line = ' 59.43.102.33:80'这样的行,地址前面有一个空格。

希望这能得到一个答案:

urllib3.util.url.parse_url(url) Given a url, return a parsed Url namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None.

https://urllib3.readthedocs.org/en/latest/helpers.html检索

相关问题 更多 >