爬取代理IP,并判断是否可用。
2024-08-29 15:06:45
# -*- coding:utf-8 -*-
from gevent import monkey
monkey.patch_all() import urllib2
from gevent.pool import Pool import requests
import re class SpiderProxy:
def __init__(self):
self.headers = {
"Host": "www.xicidaili.com",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Referer": "http://www.xicidaili.com/nn/",
}
self.url = 'http://www.xicidaili.com/nn/'
self.proxy_list = []
self.re_ip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])')
self.re_port = re.compile(r'<td>(\d+)</td>') def get_pagesource(self):
''' 取得所有1-n页上的代理IP'''
try:
num = int(raw_input('please input 1-'))
for i in range(1, num + 1):
pageurl = self.url + str(i)
req = requests.session()
html = req.get(pageurl, headers=self.headers)
ip_list = self.re_ip.findall(html.text)
port_list = self.re_port.findall(html.text)
proxy_zip = zip(ip_list, port_list)
for i in proxy_zip:
self.proxy_list.append({'http':i[0] + ':' + i[1]})
except ValueError:
print 'please input a num!'
return self.proxy_list class IsActiveProxyIP:
def __init__(self):
self.is_active_proxy_ip = [] def probe_proxy_ip(self, proxy_ip):
proxy = urllib2.ProxyHandler(proxy_ip)
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
try:
html = urllib2.urlopen('http://1212.ip138.com/ic.asp')
if html:
self.is_active_proxy_ip.append(proxy_ip)
return True
else:
return False
except Exception as e:
return False if __name__ == '__main__':
Proxy = SpiderProxy()
proxy_list = Proxy.get_pagesource()
proxy_isactive = IsActiveProxyIP()
pool = Pool(20)
pool.map(proxy_isactive.probe_proxy_ip, proxy_list)
with open(r'E:\python_demo\proxy_ip.txt', 'wb') as f:
for ip in proxy_isactive.is_active_proxy_ip:
ip = str(ip)
f.write(ip[11:-2] + '\n')
print 'file successed written'
最新文章
- Android 扫描条形码(Zxing插件)
- MUI开发APP,scroll组件,运用到区域滚动
- 【LFS】简易LFS搭建指南
- Java - NIO
- 让ABAP开发者更加轻松的若干快捷键
- 也说面试 - 一个努力的iOS Dev
- html特殊字符转义问题(转!)
- C# 零散知识 扩展方法 类型约束
- 探究linux文件
- HDU 1558 Segment set (并查集+线段非规范相交)
- 把java文件打包成.jar (jar命令详解)
- python urllib2详解及实例
- android使用apktool反编译出现Input file (d:\t) was not found or was not readable
- zabbix 监控mysql主从
- [leetcode-598-Range Addition II]
- hadoop系列三:mapreduce的使用(一)
- 入职第二天:使用koa搭建node server是种怎样的体验
- Alpha冲刺(5/10)——2019.4.27
- ejs常用功能函数
- redis 执行操作时提示(error) NOAUTH Authentication required.
热门文章
- Python 列表list 和 字符串str 互转
- 019 Remove Nth Node From End of List 删除链表的倒数第N个节点
- ubuntu apache2配置多站点
- Json 解析Json
- Java面向对象_抽象类应用——模板方法模式
- UVALive 4262——Trip Planning——————【Tarjan 求强连通分量个数】
- 从零开始的全栈工程师——js篇2.10(对象与构造函数)
- Callback, Promise和Async/Await的对比
- [转]linux C 打印当前时间
- ArcGIS for Android 中实现要素绘制时固定MapView