【Python自学笔记】requests模块添加代理&检测代理是否生效(代码)


requests添加代理

  • 直接上代码
# _*_ coding : UTF-8 _*_
# 微信公众号: xiaoqiangclub
# 开发时间: 2020/2/28  14:06
# 文件名称: diy_requests__url_response.py
# 开发工具: PyCharm
import requests
import re


def url_response(url='https://httpbin.org/ip', proxy=None):
    '''
    这是一个利用requests.get()获取response响应的函数,支持添加代理,默认没有开启代理
    :param url:url地址
    :param proxy:代理地址 格式示例:101.200.36.219:80
    :return:response响应
    '''
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    }
    # 注意:这里建议 http https 两个都添加
    proxies = {
        'http': '{}'.format(proxy),  # 设置代理:代理格式示例:223.245.38.117:65309
        'https': '{}'.format(proxy)
    }
    try:
        if proxy:
            response = requests.get(url, headers=header, proxies=proxies, timeout=10)
        else:
            response = requests.get(url, headers=header, timeout=5)
    except:
        print('访问失败,请查看您的代理或网络环境...')
        return None

    return response  #该函数放回response响应

检验代理是否生效

  • 同样直接上代码,接上部分代码

def test_proxy(response):  # 判断IP和代理是否一致
    if proxy.split(':')[0] == re.findall('(.*)', response.text)[0]:
        # if result == proxy.split(':')[0]:
        print('当前IP和设置的代理 [{}] 代理已生效...'.format(proxy))
        return True
    else:
        print('代理未生效/不可用...')
        return False


if __name__ == '__main__':
    # 以下三个url可以直接测试当前IP。任选一个即可
    # url = 'https://httpbin.org/ip'
    # url = 'http://httpbin.org/ip'
    url = 'http://icanhazip.com/'

    proxy = '118.89.234.236:8787'
    r = url_response(url, proxy=proxy)
    print(r.content.decode())
    print(r.status_code)
    test_proxy(r)  # 调用判断函数
发布了47 篇原创文章 · 获赞 1 · 访问量 1171

猜你喜欢

转载自blog.csdn.net/xiaoqiangclub/article/details/104557584