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

Tor*_*rra 13 python python-requests

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

session = requests.Session()
session.proxies = {...} # Here I want to add a single proxy
Run Code Online (Sandbox Code Playgroud)

目前,我正在遍历一堆代理,并且在每次迭代时都会创建一个新会话.我只想为每次迭代设置一个代理.

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

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

requests.get("http://example.org", proxies=proxies)
Run Code Online (Sandbox Code Playgroud)

我试图遵循这一点,但无济于事.这是我的脚本代码:

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

但是我收到一个错误:

requests.packages.urllib3.exceptions.LocationParseError: Failed to parse 59.43.102.33:80
Run Code Online (Sandbox Code Playgroud)

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

Vik*_*jha 68

除了@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
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,当我像这样设置会话的代理时,它对我来说失败了(带有`ProxyError('无法连接到代理。',OSError('隧道连接失败:403 Forbidden',))`),但是如果我通过与“get”方法完全相同的字典,它工作得很好。 (4认同)
  • 这是一种更好的方法. (2认同)
  • 啊,刚刚发现问题 - 如果您在环境中定义了其他代理,请使用 `session.trust_env=False` 以确保您为会话定义的代理不会被环境覆盖(在我的情况下,我们使用不同的代理不同的任务)。 (2认同)

小智 10

事实上,你是对的,但你必须确保你对'线'的定义,我试过这个,没关系:

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

你定义了这条线line = ' 59.43.102.33:80',地址前面有一个空格.