Request使用代理的方法(基于python)
1:首先生成可以产生新的IP地址的API链接,选择方法如下图所示:
2:添加IP白名单:
此处的ip不是电脑的ip地址,而是区域的ip地址
查询方法:
直接在百度上收索IP地址查询,收缩出来的网页上面有显示本机IP,此处的IP地址为需要填入IP白名单的IP地址
3:使用如下代码即可在使用代理的情况下进行数据的爬取(避免IP被封掉导致爬取不了内容)
import requests
# ===============获取代理ip=================
def get_ip():
url = 'http://piping.mogumiao.com/proxy/api/get_ip_bs?appKey=6226c130427f487385ad7b5235bc603c&count=5&expiryDate=0&format=2&newLine=3'
response = requests.get(url)
if response.status_code == 200:
if response.text[0] == '{':
print('获取ip失败')
else:
# 此处返回的内容是多行的字符串,使用列表表达式使其拆分成组合成列表
return [x for x in response.text.split('\n') if x]
else:
print('请求失败')
def use_proxy():
ips = get_ip()
if ips:
proxy = {'http': ips[0], 'https': ips[1]}
print(proxy)
response = requests.get('https://cd.fang.anjuke.com/loupan/all/p1/', proxies=proxy)
if response.status_code == 200:
print(response.text)
else:
print('请求失败!', response)
else:
print('获取ip失败!')
use_proxy()