爬虫爬取免费代理ip,验证代理ip有效性,保存到本地txt,建立代理池
使用多线程+队列+正则匹配,对免费代理ip网站和查询自身ip网站(验证代理ip是否有效)发送请求,如果代理ip为有效,保存至本地txt文件中,建立自己的私人有效代理ip池。
源码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import threading
from queue import Queue
import re
from bs4 import BeautifulSoup as bs
# 获取代理ip地址网址
# http://www.xsdaili.cn/dayProxy/ip/2749.html
# 验证代理ip是否有效网址
# http://www.5dip.com/5dip/QueryIp.aspx
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'}
ip_lists = []
class Spider(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
self.spider_website()
# 爬取网上免费代理ip的方法
def spider_website(self):
while not self.queue.empty():
url = self.queue.get_nowait()
r = requests.get(url=url, headers=headers, timeout=8)
if r.status_code == 200:
# print(r.status_code, r.text)
soup = bs(r.text, 'html.parser')
# print(soup)
ip_list_root = soup.find_all('div', attrs={'class': 'cont'})
# print(rr)
for ip in ip_list_root:
ipp = re.findall('<br/>(.*?)@', str(ip))
for u in ipp:
print('爬取到的网络代理地址为:' + u)
# 将爬取到的免费代理ip追加保存到列表ip_lists
ip_lists.append(u)
# 调用验证ip的方法,将爬取到的代理ip传入该方法
check_proxy(u)
def main():
q = Queue()
q.put("http://www.xsdaili.cn/dayProxy/ip/2749.html")
threads = []
thread_count = 40
for i in range(thread_count):
threads.append(Spider(q))
for t in threads:
t.start()
t.join()
# 验证代理ip是否有效
def check_proxy(use_proxy):
# print('check_proxy方法传入的ip:' + use_proxy)
spider_ip = use_proxy.split(':')[0]
# print('传入的ip切片'+spider_ip)
# 需要把ip:端口 压入到创建的字典里
proxy_real = {}
# python3.6以上的解析器,挂代理,字典的值必须添加http://或者https://
proxy_real['http'] = 'http://%s' % (use_proxy)
# proxy_real['http'] = 'http://1.174.130.57:8080'
# print(proxy_real)
try:
check_r = requests.get(url="http://www.5dip.com/5dip/QueryIp.aspx", headers=headers, proxies=proxy_real,
timeout=1.5)
# print(check_r.status_code)
if check_r.status_code == 200:
# print(check_r.text)
# rrr=check_r.text.encode('iso-8859-1').decode('gbk')
soup1 = bs(check_r.text, 'html.parser')
# print(soup1)
soup2 = re.findall('<span id="lbldqip">(.*?)</span>', str(soup1))
# print(soup2[0])
# print(type(soup2))
# print('验证网站:你的当前ip地址为:' + soup2[0])
# print('\n')
# 做一个逻辑判断,传入的代理ip和验证代理网站的ip如果一致,则说明代理是有效的
if spider_ip == soup2[0]:
print('代理ip有效------>' + soup2[0])
print('保存有效代理ip至txt文件...')
print('\n')
# 将有效代理ip保存到文本txt
f1 = open('save_live_ip.txt', 'a+')
f1.write(use_proxy + '\n')
f1.close()
except Exception as e:
print('这个代理无效....继续验证其他代理')
print('\n')
pass
if __name__ == '__main__':
f1 = open('save_live_ip.txt', 'w')
f1.close()
main()