关于Requests代理,你应该知道的

本文探讨了在Python的Requests库中如何设置和使用代理,包括不同情况下的代理配置、测试验证以及源码分析,揭示了Requests如何根据URL协议选择合适的代理,并提供了扩展知识和结论。
摘要由CSDN通过智能技术生成

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

代理主要分为以下几类:

代理分类

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

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':
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值