Python请求:仅为特定域设置代理

wwwo4jvm  于 2023-01-04  发布在  Python
关注(0)|答案(1)|浏览(113)

在Python中,有没有一种原生的方法可以让requests库只为特定的域使用代理?
就像您可以如何挂载HTTP适配器一样,但使用代理,如以下示例所示:

from requests import Session 
from requests.adapters import HTTPAdapter

s = Session()
s.mount("http://www.example.org", HTTPAdapter(max_retries=retries))
7lrncoxx

7lrncoxx1#

您可以创建一个以域为键的字典,并将代理作为关联值。
假设您对HTTPGET感兴趣,那么您只需编写一个requests.get()的 Package 器
例如:

from requests import get as GET, packages as PACKAGES
from urllib.parse import urlparse as PARSE

PACKAGES.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=1'

DOMAINS = {
    'www.bbc.co.uk': 'http://115.144.101.200:10000'
}

def http_get(url):
    proxy = DOMAINS.get(PARSE(url).netloc)
    proxies = {url: proxy} if proxy is not None else None
    print(f'{proxies=}')
    return GET(url, proxies=proxies)

print(http_get('https://news.bbc.co.uk'))
print(http_get('https://www.bbc.co.uk'))
    • 输出:**
proxies=None
<Response [200]>
proxies={'https://www.bbc.co.uk': 'http://115.144.101.200:10000'}
<Response [200]>

相关问题