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

Python 如何为请求会话对象设置单个代理?,python,python-requests,Python,Python Requests,我正在使用Python请求包发送http请求。我想向requests会话对象添加一个代理。例如 session = requests.Session() session.proxies = {...} # Here I want to add a single proxy 目前,我正在通过一系列代理进行循环,并且在每次迭代中都会创建一个新的会话。我只想为每个迭代设置一个代理 我在文档中看到的唯一示例是: proxies = { "http": "http://10.10.1.10:31

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

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

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

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

>>> import requests
>>> s = requests.Session()
>>> s.get("http://www.baidu.com", proxies={'http': 'http://10.11.4.254:3128'})
<Response [200]>
导入请求 >>>s=请求。会话() >>>s.get(“http://www.baidu.com,代理={'http':'http://10.11.4.254:3128'})
您是否像
line='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

希望这能带来一个答案:

urllib3.util.url.parse_url(url) 给定一个url,返回一个名为tuple的解析url。尽最大努力解析不完整的URL。未提供的字段将为“无”


检索到,除了您目前获得的解决方案外,您还可以通过其他方式设置代理:

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)

每行开头都有一个空格。这总是最简单的事情,让我最开心。谢谢:)注意:如果你使用代理服务器,例如squid,这不会让你使用相同的IP地址。i、 e.后续的
s.get
将使用原始代理/实际ip。这是一种更好的方法。谢谢@BugHunterUKMany谢谢!这对我来说是更好的回答。在所有下一个请求中使用代理,当我像这样设置会话的代理时,它对我来说失败(带有
ProxyError('cannotconnect to proxy')、OSError('Tunnel connection failed:403 probled'))
),但是如果我将完全相同的dict传递给
get
方法,它工作得很好。啊,刚刚发现问题-如果您在环境中定义了其他代理,请使用
session.trust_env=False
确保为会话定义的代理不被环境覆盖(在我的情况下,我们为不同的任务使用不同的代理)。这与上面答案中的
s.proxies.update(proxies)
有何不同?