import requests
import queue
import threading
from lxml import etree #要爬取的URL
url = "http://xxxxx" #代理ip网站
proxy_url = "https://www.kuaidaili.com/free/inha/{page}/" class MyThreadPool:
def __init__(self, maxsize):
self.maxsize = maxsize
self._pool = queue.Queue(maxsize)
for _ in range(maxsize):
self._pool.put(threading.Thread) def get_thread(self):
return self._pool.get() def add_thread(self):
self._pool.put(threading.Thread) def get_url(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
}
response = requests.get(url,headers=headers)
html_str = response.text
return html_str def proxy_get_url(url,prox):
proxies = {}
proxies["http"] = prox
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
}
response = requests.get(url,headers=headers,proxies=proxies,timeout=3)
html_str = response.text
return html_str def ip_proxy(html_str):
html = etree.HTML(html_str)
ip_list = html.xpath('//tr/td[@data-title="IP"]/text()')
port_list = html.xpath('//tr/td[@data-title="PORT"]/text()')
http_list = []
for i in range(len(ip_list)):
http_proxy = ip_list[i]+":"+port_list[i]
http_list.append(http_proxy)
return http_list def available_ip(ip_list):
for ip in ip_list:
try:
proxy_get_url('https://www.baidu.com/',ip)
except Exception as e:
continue
IP_LIST.append(ip) if __name__ == "__main__":
IP_LIST = []
pool = MyThreadPool(20) #线程池数
#验证代理ip
for i in range(1,20): #页数
page_ip = get_url(proxy_url.format(page=i))
ip_list = ip_proxy(page_ip)
t = pool.get_thread()
obj = t(target=available_ip,args=(ip_list,))
obj.start() #爬取网站
for ip in IP_LIST:
try:
proxy_get_url(url,ip)
except Exception as e:
continue
print(ip)
#使用一个ip爬取网站,如果ip不可用了删除ip
while IP_LIST:
    try:
print(IP_LIST[0])
proxy_get_url(url,IP_LIST[0])
except Exception as e:
del IP_LIST[0]
continue

  

最新文章

  1. 06.LoT.UI 前后台通用框架分解系列之——浮夸的图片上传
  2. 11月14日用AJAX、PHP、SESSION做购物车
  3. Note3 :《集体智慧编程》用户相似度计算
  4. android遥控器的映射
  5. Hibernate事务与并发问题处理(乐观锁与悲观锁)
  6. 如何使用 RDP 或 SSH 连接到 Azure 虚拟机
  7. 应用程序无法正常启动0xc0150002 解决方式
  8. Sql Server使用技巧
  9. Android Service之LOCATION_SERVICE
  10. asp.net DropDownList的AppendDataBoundItems属性
  11. sharepoint 2013基于AD的Form表单登录(三)——选择用户时,屏蔽掉AD。
  12. angular2 日期格式化
  13. [翻译]成为顶尖程序员应当学什么?Python、C还是Ruby?
  14. 详解Ajax请求(二)——异步请求原理的分析
  15. Robot Framework自动化_Selenium2Library 关键字
  16. BlockQueue 解析
  17. stderr和stdout详细解说
  18. 【RL-TCPnet网络教程】第30章 RL-TCPnet之SNTP网络时间获取
  19. arc 097 E - Sorted and Sorted
  20. 利用python操作excel

热门文章

  1. app前端代码打包步骤
  2. WiFi-ESP8266入门http(1)-建立服务器,直接发送网
  3. SWAP_JOIN_INPUTS Oracle Hint(处理hash join强制大表(segment_size大)作为被驱动表)
  4. wxWidgets 在 Windows 下开发环境配置
  5. Edusoho之LAMP环境搭建
  6. 带返回结果的批量任务执行 CompletionService
  7. Linux常用命令全称
  8. vue 2.0多页面开发
  9. Java过滤掉字符串中的html标签、style标签、script标签
  10. ML.NET 示例:推荐之One Class 矩阵分解