爬虫(五):requests模块使用代理

爬虫(五):requests模块使用代理
爬虫(五):requests模块使用代理

使用方法:

requests.get(‘http://www.baidu.com’,proxies=proxies)
proxies的形式为字典
proxies={
“http”:“http://12,34,56,78:8080”
或者:
“https”:“https://12,34,56,78:8080”
}

为什么使用代理
- 让服务器以为不是同一个客户端请求
- 防止真实地址泄露

例子:

import requests
'''
proxies代理ip
'''
def run():
    header = {
        'User-Agent': 'ozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
    }
    proxies = {
        "http": "101.4.136.34:80"
    }
    r = requests.get('http://www.baidu.com', proxies=proxies, headers=header)
    print(r.status_code)


if __name__ == '__main__':
    run()

#####使用代理ip

  • 1.准备一堆ip,组成ip池,随机选择一个ip来使用
  • 如何随机选择代理ip
    • 对每个ip建立字典,包含ip和使用次数{‘ip’:‘xx’,‘times’:‘xx’},生成一个列表[{},{},{},…]然后按照times对其进行排序,选择使用次数较少的10个ip,从其中随机选择一个
      -2. 检查ip的可用性两种方法
    • 使用requests添加超时参数,判断ip地址的质量
    • 在线代理ip质量检测的网站