自动爬取代理IP例子
import time
import json
import datetime
import threading
import requests
from lxml import etree
from queue import Queue # 爬取免费代理IP 来源xicidaili.com
# 多线程验证代理ip是否可用
class ProxyTest:
def __init__(self):
self.test_url = "http://pv.sohu.com/cityjson?ie=utf-8"
self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",}
self.request_queue = Queue() def parse_url(self, url, proxies, timeout=3):
return requests.get(url, headers=self.headers, proxies=proxies, timeout=timeout).content.decode() # 请求
def request(self):
while True:
# 获取ip地址
ip = self.request_queue.get() # 发起请求
try:
starttime = datetime.datetime.now()
html_str = self.parse_url(self.test_url, proxies={"http": ip}, timeout=5)
endtime = datetime.datetime.now()
use_time = endtime - starttime
except Exception as e:
# 请求超时
print("timeout %s" % ip)
self.request_queue.task_done()
continue # 检查返回html
try:
json_dict = json.loads(html_str[19:-1])
except:
print("fail %s, use time %d" % (ip, use_time.seconds))
self.request_queue.task_done()
continue if ip.startswith("http://"+json_dict["cip"]):
# 代理可用
print("success %s, use time %d, %s" % (ip, use_time.seconds, html_str))
self.request_queue.task_done()
# 保存到文件
with open("proxy_ok_ip.json", "a", encoding="utf-8") as f:
f.write(ip)
f.write("\n")
else:
# ip不是高匿代理
print("%s invalid, use time %d" % (ip, use_time.seconds))
self.request_queue.task_done() def run(self):
# 读取ip地址文件 并存储到队列中
with open("proxy.json", "r", encoding="utf-8") as f:
for line in f:
self.request_queue.put(line.strip()) # 遍历,发送请求,获取响应
for i in range(30):
# daemon=True 把子线程设置为守护线程,该线程不重要主线程结束,子线程结束
threading.Thread(target=self.request, daemon=True).start() self.request_queue.join() #让主线程等待阻塞,等待队列的任务完成之后再完成 print("主线程结束") class Proxy:
def __init__(self):
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
} def start_urls_superfastip(self):
return ["http://www.superfastip.com/welcome/freeip/%d" % i for i in range(1,11)] def get_content_list_superfastip(self, html_str):
content_list = []
html = etree.HTML(html_str)
tr_list = html.xpath('/html/body/div[3]/div/div/div[2]/div/table/tbody/tr')
for tr in tr_list:
if tr.xpath('./td[4]/text()')[0].strip() == 'HTTP':
item = {}
item["ip"] = tr.xpath('./td[1]/text()')[0].strip()
item["port"] = tr.xpath('./td[2]/text()')[0].strip()
content_list.append(item) return content_list def start_urls_xici(self):
return ["http://www.xicidaili.com/nn/%d" % i for i in range(1,6)] def get_content_list_xici(self, html_str):
content_list = []
html = etree.HTML(html_str)
tr_list = html.xpath('//table[@id="ip_list"]/tr')[1:]
for tr in tr_list:
item = {}
item["ip"] = tr.xpath('./td[2]/text()')[0].strip()
item["port"] = tr.xpath('./td[3]/text()')[0].strip()
content_list.append(item)
return content_list def start_urls_kuaidaili(self):
return ["https://www.kuaidaili.com/free/inha/%d/" % i for i in range(1, 11)] def get_content_list_kuaidaili(self, html_str):
content_list = []
html = etree.HTML(html_str)
tr_list = html.xpath('//div[@id="list"]/table/tbody/tr')
for tr in tr_list:
item = {}
item["ip"] = tr.xpath('./td[1]/text()')[0].strip()
item["port"] = tr.xpath('./td[2]/text()')[0].strip()
content_list.append(item)
return content_list def start_urls_89ip(self):
return ["http://www.89ip.cn/index_%d.html" % i for i in range(1, 11)] def get_content_list_89ip(self, html_str):
content_list = []
html = etree.HTML(html_str)
tr_list = html.xpath('//div[@class="layui-form"]/table/tbody/tr')
for tr in tr_list:
item = {}
item["ip"] = tr.xpath('./td[1]/text()')[0].strip()
item["port"] = tr.xpath('./td[2]/text()')[0].strip()
content_list.append(item)
return content_list def parse_url(self, url):
return requests.get(url, headers=self.headers).content.decode() def save_content_list(self, content_list):
with open("proxy.json", "a", encoding="utf-8") as f:
for ip in content_list:
f.write("http://%s:%s" % (ip["ip"], ip["port"]))
f.write("\n") def run(self):
# 构造请求地址列表
start_urls_xici = self.start_urls_xici()
start_urls_89ip = self.start_urls_89ip()
start_urls_kuaidaili = self.start_urls_kuaidaili()
start_urls_superfastip = self.start_urls_superfastip() all_content_list = [] # 存放所有爬取到的ip for url in start_urls_superfastip:
html_str = self.parse_url(url) # 获取响应
content_list = self.get_content_list_superfastip(html_str) # 处理响应
all_content_list.extend(content_list) # 将结果加到列表里
time.sleep(0.2) for url in start_urls_xici:
html_str = self.parse_url(url) # 获取响应
content_list = self.get_content_list_xici(html_str) # 处理响应
all_content_list.extend(content_list) # 将结果加到列表里
time.sleep(0.2) for url in start_urls_kuaidaili:
html_str = self.parse_url(url)
content_list = self.get_content_list_kuaidaili(html_str)
all_content_list.extend(content_list)
time.sleep(0.2) for url in start_urls_89ip:
html_str = self.parse_url(url)
content_list = self.get_content_list_89ip(html_str)
all_content_list.extend(content_list)
time.sleep(0.2)
print("抓取完成")
self.save_content_list(all_content_list) if __name__ == '__main__':
# 抓取数据
spider = Proxy()
spider.run() # 检测ip是否可用
proxy = ProxyTest()
proxy.run()
print("最后可以用的代理IP在proxy_ok_ip.json")
自动爬取代理IP例子的更多相关文章
- python爬虫爬取代理IP
# #author:wuhao # #--*------------*-- #-****#爬取代理IP并保存到Excel----#爬取当日的代理IP并保存到Excel,目标网站xicidaili.co ...
- python 批量爬取代理ip
import urllib.request import re import time import random def getResponse(url): req = urllib.request ...
- 使用Python爬取代理ip
本文主要代码用于有代理网站http://www.kuaidaili.com/free/intr中的代理ip爬取,爬虫使用过程中需要输入含有代理ip的网页链接. 测试ip是否可以用 import tel ...
- 爬虫爬取代理IP池及代理IP的验证
最近项目内容需要引入代理IP去爬取内容. 为了项目持续运行,需要不断构造.维护.验证代理IP. 为了绕过服务端对IP 和 频率的限制,为了阻止服务端获取真正的主机IP. 一.服务器如何获取客户端IP ...
- python代理池的构建3——爬取代理ip
上篇博客地址:python代理池的构建2--代理ip是否可用的处理和检查 一.基础爬虫模块(Base_spider.py) #-*-coding:utf-8-*- ''' 目标: 实现可以指定不同UR ...
- 爬取代理IP
现在爬虫好难做啊,有些网站直接封IP,本人小白一个,还没钱,只能找免费的代理IP,于是去爬了西刺免费代理,结果技术值太低,程序还没调试好, IP又被封了... IP又被封了... IP又被封了... ...
- 爬取代理IP,并判断是否可用。
# -*- coding:utf-8 -*- from gevent import monkey monkey.patch_all() import urllib2 from gevent.pool ...
- Python爬取代理ip
# -*- coding:utf-8 -*- #author : willowj import urllib import urllib2 from bs4 import BeautifulSoup ...
- 原创:Python爬虫实战之爬取代理ip
编程的快乐只有在运行成功的那一刻才知道QAQ 目标网站:https://www.kuaidaili.com/free/inha/ #若有侵权请联系我 因为上面的代理都是http的所以没写这个判断 代 ...
随机推荐
- 2019-11-29-C#-很少人知道的科技
title author date CreateTime categories C# 很少人知道的科技 lindexi 2019-11-29 10:12:43 +0800 2018-03-16 08: ...
- linux 桥接模式下 固定ip 设置
DEVICE=eht0 #网卡名称BOOTPROTO=none #关闭自动获取 dhcp IPADDR=192.168.0.178 #ip地址GATEWAY=192.168.0.1 DN ...
- SecureCRT文件和文件夹显示不同颜色(像linux中那样效果)
如何设置secureCRT使用的他可以像linux文件和文件夹显示不同的颜色呢 原先显示效果如下: 效果图 配置
- 使用IL DASM来查看接口内的自动属性
在我的本地地址中 C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.2 Tools\x64下有一个文件 ildas ...
- Ubuntu16.04下caffe CPU版的详细安装步骤
一.caffe简介 Caffe,是一个兼具表达性.速度和思维模块化的深度学习框架. 由伯克利人工智能研究小组和伯克利视觉和学习中心开发. 虽然其内核是用C++编写的,但Caffe有Python和Mat ...
- etl-p
java excel 导入数据库 上传文件包 解压导入excel包 导入mysql
- java医院交费机
1.读卡器 钱币识别器 身份证识别等 2.与银行交互 socket客户端 发送 10001 返回解析 查询余额 密码发送 3.界面展示freemaker ftl文件展示 4.hql语句 5.webse ...
- 下载bat脚本
@rem 注释:从ftp服务器每小时下载北向性能文件的脚本 @rem 用vb脚本取昨天 for /f %%a in ('cscript //nologo yester.vbs') do set yes ...
- java数据结构3--List
List 1.1 list接口的简介 1.2 list实现子类 ArrayList:线程不安全,查询速度快,底层用的是数组,增删慢LinkedList:线程不安全,链表结构,增删速度快,查询慢Vect ...
- 【NOIP2016提高A组模拟8.14】总结
第一题是几何题,没去想直接弃疗.... 第二题觉得很像背包,但是单挑人的顺序不同,答案也会不同,我比较了每个人先后的优劣性,成功搞定了这道题.但是再输出时不小心搞错了,爆零. 第三题,我答案了整整一个 ...