繁体   English   中英

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

[英]How can I set a single proxy for a requests session object?

我正在使用 Python requests 包发送 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

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

除了@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 line = ' 59.43.102.33:80'类的line = ' 59.43.102.33:80' ,地址前面有一个空格。

除了目前已有的解决方案外,您还可以通过其他方式设置代理:

import requests

with requests.Session() as s:
    # either like this
    s.proxies = {'https': 'http://105.234.154.195:8888', 'http': 'http://199.188.92.69:8000'}
    # or like this
    s.proxies['https'] = 'http://105.234.154.195:8888'
    r = s.get(link)

希望这可能会导致答案:

urllib3.util.url.parse_url(url) 给定一个 url,返回一个解析后的 Url 命名元组。 尽力解析不完整的 url。 未提供的字段将为 None。

取自https://urllib3.readthedocs.org/en/latest/helpers.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM