如何为请求会话对象设置单个代理? [英] How can I set a single proxy for a requests session object?

查看:34
本文介绍了如何为请求会话对象设置单个代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

session = requests.Session()session.proxies = {...} # 这里我想添加一个代理

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

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

代理 = {"http": "http://10.10.1.10:3128","https": "http://10.10.1.10:1080",}requests.get("http://example.org", proxies=proxies)

我曾尝试遵循此方法,但无济于事.这是我的脚本代码:

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

但我收到一个错误:

requests.packages.urllib3.exceptions.LocationParseError: 无法解析 59.43.102.33:80

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

解决方案

其实你说得对,但是你要保证你对'line'的定义,这个我试过了,没问题:

<预><代码>>>>进口请求>>>s = requests.Session()>>>s.get("http://www.baidu.com", proxies={'http': 'http://10.11.4.254:3128'})<响应[200]>

你是否定义了类似line = ' 59.43.102.33:80'的行,地址前面有一个空格.

I'm using the Python requests package to send http requests. I want to add a single proxy to the requests session object. eg.

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

Currently I am looping through a bunch of proxies, and at each iteration a new session is made. I only want to set a single proxy for each iteration.

The only example I see in the documentation is:

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

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

I've tried to follow this, but to no avail. Here is my code from the script:

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

But I get an error:

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

How is it possible to set a single proxy on a session object?

解决方案

In fact, you are right, but you must ensure your defination of 'line', I have tried this , it's ok:

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

Did you define the line like line = ' 59.43.102.33:80', there is a space at the front of address.

这篇关于如何为请求会话对象设置单个代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆