簡體   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