【Python爬虫实例学习篇】-2.获取免费IP代理由于使用爬虫时经常会查IP地址,所以需要找一个获得IP被代理的地方。经过一番风骚操作,终于搭建了自己的第一个代理库,代理库的返回值类型都是列表类型。(注意,这些免费代理每天实时更新,经测试可用率超过60%)另外,为了保证代理库能够长期稳定运行,本文封装了再次请求图书馆。使用工具1.Python3.62.requests库3.免费代理网站目录API获取免费代理API获取免费代理网页获取免费代理网页获取免费代理网页获取免费代理页面(推荐)重新封装GET请求结果展示1.获取免费代理的API本免费代理网站提供两种,一种是提供免费代理,一种是提供一页免费代理(每页最多15个)。importrequestsdefGetFreeProxy():#获取免费代理url='https://www.freeip.top/api/proxy_ip'ip=list(range(1))try:res=requests.get(url=url,timeout=20)#用json解析返回的数据result=res.json()ip[0]=result['data']['ip']+':'+result['data']['port']returnipexceptException:print('Failedtogettheproxyip!Retrying...')#ExceptionretuningGetFreeProxy()return02.API获取免费代理页面defGetFreeProxyListAPI(page=1,country='',isp='',order_by='validated_at',order_rule='DESC'):#获取免费代理列表#返回值为list#必须传递参数名称数据类型说明example#pageintNPage1#countrystringNChina,UnitedStates#ispstringNISPTelecom,AlibabaCloud#order_bystringN排序字段speed:响应速度,validated_at:最新验证时间created_at:生存时间#order_rulestringN排序directionDESC:降序ASC:升序data={'page':str(page),'国家':国家,'isp':isp,'order_by':order_by,'order_rule':order_rule}url='https://www.freeip.top/api/proxy_ips'+'?+str(parse.urlencode(data))ip=list(range(1))headers={'User-Agent':str(choice(user_agent_list))}session=requests.session()res=GET(session,url=url,headers=headers)#解析数据result=res.json()ip=list(range(int(result['data']['to'])))foriinrange(int(result['data']['to'])):ip[i]=result['data']['data'][i]['ip']+':'+result['data']['data'][i]['port']returnip3、网页获取一个免费代理defGetFreeProxy():#method=2ispure-HTTP#返回值为listheaders={'User-Agent':str(random.choice(user_agent_list))}session=requests.session()#选择代理网站homeurl='https://www.freeip.top/'url='https://www.freeip.top/?page='GET(session=session,url=homeurl,headers=headers)#//tr[1]/td[1]res=GET(session=session,url=url,headers=headers)html=etree.HTML(res.text)#选择IP数据和端口数据IP_list_1=html.xpath('//tr[1]/td[1]')IP_list_2=html.xpath('//tr[1]/td[2]')IP_list=list(range(1))IP_list[0]=IP_list_1[0].text+':'+IP_list_2[0].textreturnIP_list4.从网页获取免费代理的页面(推荐)defGetFreeProxyList(GetType=1,protocol='https'):#代理可用率超过50%,推荐使用#method=2ispure-HTTP#返回值为listheaders={'User-Agent':str(choice(user_agent_list)),}session=requests.session()#选择代理ifGetType==1:homeurl='https://www.freeip.top/'url='https://www.freeip.top/?page=1&protocol='+protocolGET(session=session,url=homeurl,headers=headers)elifGetType==2:homeurl='https://www.kuaidaili.com/'url='https://www.kuaidaili.com/free/inha/'GET(session=session,url=homeurl,headers=headers)else:print('暂不支持其他方式!')return0#获取IP列表num=1if_exists('IP.txt'):remove('IP.txt')IP_list=[]whileTrue:res=GET(session=session,url=url,headers=headers)html=etree.HTML(res.content.decode('utf-8'))#选择IP数据和端口数据IP_list_1=html.xpath('//tr/td[1]')IP_list_2=html.xpath('//tr/td[2]')如果GetType==1:url='https://www.freeip.top/?page='+str(num)+'&protocol='+protocolIP_list.extend(list(map(lambdaip_list_1,ip_list_2:(ip_list_1.text+':'+ip_list_2.text),IP_list_1,IP_list_2)))num=num+1iflen(IP_list_1):continueelse:breakreturnIP_list5.重新封装GET请求#由于免费代理网站不稳定,容易出现503当获取大量代理时报错,所以需要多次重传defGET(session,url,headers,timeout=15,num=0):try:response=session.get(url=url,headers=headers,timeout=timeout,verify=False)ifresponse.status_code==200:returnresponseelse:print('对方服务器错误,%i'%(num+1)+'次重试是进行中···')sleep(0.8)response=GET(session=session,url=url,headers=headers,num=num+1)returnresponseexceptException:print('Connectionerror,%i'%(num+1)+'retries...')sleep(0.8)response=GET(session=session,url=url,headers=headers,num=num+1)returnresponse6.结果显示获取免费代理:获取免费代理页面:==微信公众号:==