Python实现爬取可用代理IP

  在实现爬虫时,动态设置代理IP可以有效防止反爬虫,但对于普通爬虫初学者需要在代理网站上测试可用代理IP。由于手动测试过程相对比较繁琐,且重复无用过程故编写代码以实现动态抓取可用的代理IP。动态代理IP保存在Json文件中,以供后续具体项目爬虫使用,但所爬取的代理IP是免费IP,所以可能出现当时爬取能用,过一段时间无法使用的情况。

 1) 先从西刺代理网站上爬取前10页,速度较快的IP,保存到proxies数组中,其中proxy使用的是requests.get()可直接使用字典格式 

 1 print("Start find proxy in xichi...")
 2 headers = {
 3     'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
 4                   'AppleWebKit/537.36 (KHTML, like Gecko) '
 5                   'Chrome/60.0.3112.101 Safari/537.36'
 6 }
 7 # 保存西刺代理的IP汇总数组
 8 proxies = []
 9 for num in range(1,10):
10     # 西刺代理网站
11     response = requests.get("http://www.xicidaili.com/nn/%d"%(num),headers=headers)
12     soup = BeautifulSoup(response.text,"lxml")
13     ipInfos = soup.select('#ip_list > tr')
14 
15     for ipInfo in ipInfos[1:]:
16         ipInfo = ipInfo.select("td")
17         if ipInfo[6].select("div > div")[0].get("class")[1] == "fast":
18             # 处理网页代理信息数据
19             ip = ipInfo[1].get_text().strip()
20             port = ipInfo[2].get_text().strip()
21             prc = ipInfo[5].get_text().strip().lower()
22             # 组合成requests要求的代理参数格式,格式字典形式如下
23             # proxies = {'https':'https://112.114.93.50:8118','http':'https://122.72.18.34:80'}
24             # 协议:协议://ip:端口
25             proxy = dict()
26             proxy[prc] = prc + "://" + ip + ":" + port
27             proxies.append(proxy)
28     time.sleep(random.randint(1, 5))
29 
30 print("proxies counts is %d"%(len(proxies)))

  2) 使用proxies,模拟浏览器打开百度首页,如果返回status_code为200,就认为此代理可用,即可保存后续使用。 

 1 print("Starting test proxies...")
 2 
 3 # 记录当前已找到可用IP数目
 4 okIpNum = 0
 5 for proxy in proxies:
 6     # 随机使用不同的userAgent
 7     userList = userAgentList.userList
 8     headers = {'User-Agent': userList[random.randint(0, len(userList)-1)]}
 9     # request发送请求时使用不同的userAgent,同时带入测试IP代理
10     # 如出现异常则直接跳过,可能出现连接超市的异常等
11     try:
12         text_web = requests.get("https://www.baidu.com/",headers = headers, proxies = proxy)
13     except:
14         print(proxy," unuseable")
15         continue
16 
17     if text_web.status_code == 200:
18         with open(filename, "a+") as f:
19             js = json.dumps(proxy)
20             f.write(js)
21         print(proxy, "useable")
22         okIpNum += 1
23     # 判断已经找到可食用的IP数目,从而退出程序
24     if okIpNum == needCount:
25         print("Already find %d useable proxies"%(okIpNum))
26         break
27 
28     time.sleep(random.randint(1,3))

  此爬取方法还是用动态设置UserAgent,以及爬取过程随机sleep,以避免被服务器禁用。

猜你喜欢

转载自www.cnblogs.com/henley0000/p/9356928.html