一、需求场景:

1、由于业务需要,会频繁地购买或更换HTTPS类型的代理。

2、购买到的代理会出现所属地区不正确或不可用等问题,每次都需要测试无误后才能交付。

3、起初都是人工操作,“使用Proxifier填上代理信息-->清缓存-->访问测试IP的网站”,多的时候一天会有近千条需要测试。

二、想法:

用Python爬虫挂上代理去抓取IP网站的信息,将正确结果依次返回(使用多线程加快爬取速度)。

三、实践:

#-*-coding:utf-8-*-importtimeimportrequestsfrombs4importBeautifulSoupfromthreadingimportThread,Locklock=Lock()ipaddress=0country=0bad=0url="https://whatismyipaddress.com/"kv={'User-Agent':'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36\(KHTML,likeGecko)Chrome/64.0.3282.186Safari/537.36'}classGetProxiesThread(Thread):def__init__(self,url,kv,proxy,proxies):self.url=urlself.kv=kvself.proxy=proxyself.proxies=proxiessuper(GetProxiesThread,self).__init__()defrun(self):check_proxies(self.url,self.kv,self.proxy,self.proxies)defcheck_proxies(url,kv,proxy,proxies):globalipaddress,country,bad,seqtry:r=requests.get(url,headers=kv,proxies=proxies)r.raise_for_status()r.encoding=r.apparent_encodingsoup=BeautifulSoup(r.text,'lxml')ipaddress=soup.select('#section_leftdiva')[0].textcountry=soup.body.table.contents[-2].td.stringlock.acquire()print("{}==>{}".format(ipaddress,country))exceptExceptionasreason:lock.acquire()bad+=1print(reason)print("{}isunavailable!".format(proxy))finally:lock.release()defmain():num=0start=time.time()withopen('proxieslist.txt','r')asf:threads=[]forlineinf:num+=1proxy=''.join(line.splitlines())https_proxy='https://'+proxyproxies={"https":https_proxy}t=GetProxiesThread(url,kv,proxy,proxies)threads.append(t)t.start()time.sleep(0.6)fortinthreads:t.join()print("Thetotalamount:%s"%(num))print("Notavailablequantity:%s"%(bad))print("Elapsedtime:%s"%(time.time()-start))if__name__=='__main__':main()

四、存在的问题:

1、可以添加将结果写入到记事本的功能。

2、有时候运行到一半会卡主,原因不明。