1 import requests 2 import random 3 4 # 请求发送的网址url 5 url = 'https://www.baidu.com' 6 # 请求头信息,通常用于伪装浏览器,通过服务器校验 7 headers = { 8 9 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36' 10 } 11 # 创建一个代理ip池,里面存储各个代理ip的字典数据({'协议':'ip:port'}) 12 proxies = [{'http': '127.0.0.0:8888'}, {'https': '127.0.0.1:8848'}] 13 14 # get请求需要携带的参数(url后面的参数) 15 params = {} 16 17 requests.get(url=url, params=params, headers=headers, proxies=random.choice(proxies)) #随机切换代理ip 18 # post请求需要携带的参数(form中的参数) 19 data = {} 20 requests.post(url=url, data=data, headers=headers, proxies=random.choice(proxies)) 21 22 # 创建一个session请求对象,跟requests用法一样,可以发送get,post请求,并可以把cookie等设置存储在session对象中 23 sess = requests.Session()