关于Requests代理,你必须知道的

关于Requests代理,你必须知道的

说到代理,写过爬虫的小伙伴一定都不陌生。但是你的代理真的生效了么

代理主要分为以下几类:

代理分类

如果是爬虫的话,最常见的选择是高匿代理。

Requests 设置代理非常方便,只需传递一个 proxies 参数即可。如官方示例:

import requests

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

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

留意一个地方,proxies 字典中有两个 key :https 和 http,为什么要写两个 key,如果只有一个可以么?

试试就知道了

准备验证函数

这个函数会使用代理去访问两个 IP 验证网站,一个是 https,一个是 http。

import requests
from bs4 import BeautifulSoup


def validate(proxies):
    https_url = 'https://ip.cn'
    http_url = 'http://ip111.cn/'
    headers = {'User-Agent': 'curl/7.29.0'}
    https_r = requests.get(https_url, headers=headers, proxies=proxies, timeout=10)
    http_r = requests.get(http_url, headers=headers, proxies=proxies, timeout=10)
    soup = BeautifulSoup(http_r.content, 'html.parser')
    result = soup.find(class_='card-body').get_text().strip().split('''\n''')[0]

    print(f"当前使用代理:{proxies.values()}")
    print(f"访问https网站使用代理:{https_r.json()}")
    print(f"访问http网站使用代理:{result}")

测试

  • Case 1

    proxies = {
        'http': '222.189.244.56:48304',
        'https': '222.189.244.56:48304'
    }
    validate(proxies)

    输出

    当前使用代理:dict_values(['222.189.244.56:48304', '222.189.244.56:48304'])
    访问https网站使用代理:{'ip': '222.189.244.56', 'country': '江苏省扬州市', 'city': '电信'}
    访问http网站使用代理:222.189.244.56 China / Nanjing

    结果: 访问两个网站均使用了代理

  • Case 2

    扫描二维码关注公众号,回复: 7067002 查看本文章
    proxies = {
        'http': '222.189.244.56:48304'
    }
    validate(proxies)

    输出

    当前使用代理:dict_values(['222.189.244.56:48304'])
    访问https网站使用代理:{'ip': '118.24.234.46', 'country': '重庆市', 'city': '腾讯'}
    访问http网站使用代理:222.189.244.56 China / Nanjing

    结果: 只有http请求使用了代理

  • Case 3

    proxies = {
        'https': '222.189.244.56:48304'
    }
    validate(proxies)

    输出

    当前使用代理:dict_values(['222.189.244.56:48304'])
    访问https网站使用代理:{'ip': '222.189.244.56', 'country': '江苏省扬州市', 'city': '电信'}
    访问http网站使用代理:118.24.234.46 China / Nanning

    结果: 只有https请求使用了代理

其他测试

通过 wireshark 抓包发现,当协议不匹配时,根本不会向代理服务器发起请求。

通过 postman 测试,结果与 Requests 一致,协议不同的情况下,不会走代理。

猜测可能是一种约定或者规则,类似 PAC ?(如果你知道答案,请告诉我)

结论

** 在 Requests 中,代理必须和目标网站具有相同的协议(http / https)的时候,才能生效。**

参考链接

猜你喜欢

转载自www.cnblogs.com/ljz-2014/p/11387488.html