建立爬虫代理IP池
单线程构建爬虫代理IP池
#!/usr/bin/python3.5
# -*- coding:utf-8 -*- import time
import tempfile
from lxml import etree
from urllib import request user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0' def get_content(url): # 获取网页内容
global user_agent
headers = {'User-Agent': user_agent}
req = request.Request(url=url, headers=headers)
res = request.urlopen(req)
return res.read().decode('utf-8') def get_info(tmp,content): # 提取网页信息 / ip 端口
ip_list = etree.HTML(content).xpath('//table[contains(@id,"ip_list")]/tr/td[2]/text()')
port_list = etree.HTML(content).xpath('//table[contains(@id,"ip_list")]/tr/td[3]/text()')
for i in range(0,len(ip_list)):
out = u""
out += u"" + ip_list[i]
out += u":" + port_list[i]
tmp.write((out + u"\n").encode('utf-8')) # 所有ip和端口号写入data文件 def verify_ip(ip,port,test_url): # 验证 ip+port 有效性
global user_agent
headers = {'User-Agent': user_agent,'Host': 'www.12306.cn','Referer': 'http://www.12306.cn/'}
proxy = {'http':'http://%s:%s'%(ip,port)}
print(proxy) proxy_handler = request.ProxyHandler(proxy)
opener = request.build_opener(proxy_handler)
request.install_opener(opener) req = request.Request(url=test_url,headers=headers)
time.sleep(1)
try:
res = request.urlopen(req)
time.sleep(2)
content = res.read()
if content:
print('{0}:{1} is ok'.format(ip,port))
with open("proxy_info.txt", "a") as fd: # 可用ip+port保存到proxy_info.txt文件中
fd.write(ip + u":" + port + "\n")
else:
print('{0}:{1} is unavailable'.format(ip,port))
except request.URLError as e:
print(e.reason) def verify_ip2(ip,port,test_url):
import requests
try:
response = requests.get(test_url,proxies={'http':'http://{0}:{1}'.format(ip,port)},timeout=2)
# print(response.status_code)
except Exception as e:
print("{0}:{1} failed".format(ip,port),e)
else:
print("{0}:{1} is ok".format(ip,port))
with open("proxy_info.txt", "a") as fd: # 可用ip+port保存到proxy_info.txt文件中
fd.write(ip + u":" + port + "\n") if __name__ == '__main__':
url = 'http://www.xicidaili.com/nn/'
test_url = "http://httpbin.org/"
url_list = [ url + str(i) for i in range(1,2) ]
tmp = tempfile.TemporaryFile()
for url in url_list:
content = get_content(url)
time.sleep(2)
get_info(tmp,content) tmp.seek(0)
for item in tmp.readlines():
item = item.decode('utf-8')
# verify_ip(item.split(u":")[0],item.split(u":")[1].strip(),test_url)
verify_ip2(item.split(u":")[0],item.split(u":")[1].strip(),test_url)
tmp.close()
使用线程池加快验证代理的速度
concurrent.futures.ThreadPoolExecutor
#!/usr/bin/python3.5
# -*- coding:utf-8 -*- import time
import tempfile
from lxml import etree
from urllib import request
from concurrent.futures import ThreadPoolExecutor user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0'
ip2port = [] def get_content(url): # 获取网页内容
global user_agent
headers = {'User-Agent': user_agent}
req = request.Request(url=url, headers=headers)
res = request.urlopen(req)
return res.read().decode('utf-8') def get_info(tmp, content): # 提取网页信息 / ip 端口
ip_list = etree.HTML(content).xpath('//table[contains(@id,"ip_list")]/tr/td[2]/text()')
port_list = etree.HTML(content).xpath('//table[contains(@id,"ip_list")]/tr/td[3]/text()')
for i in range(0, len(ip_list)):
out = u""
out += u"" + ip_list[i]
out += u":" + port_list[i]
tmp.write((out + u"\n").encode('utf-8')) # 所有ip和端口号写入data文件 def verify_ip(ip, port, url):
ret = { 'code':-1,'ipport':None }
import requests
try:
response = requests.get(url, proxies={'http': 'http://{0}:{1}'.format(ip, port)}, timeout=3)
print('{}:{} --> {}'.format(ip,port,response.status_code))
except Exception as e:
# print("{0}:{1} failed".format(ip, port), e)
pass
else:
# print("{0}:{1} is ok".format(ip, port))
if 200 == response.status_code:
ret['code'] = 0
ret['ipport'] = '{0}:{1}'.format(ip,port)
finally:
return ret def callback(future):
global ip2port
ret = future.result()
if 0 == ret['code']:
ip2port.append(ret['ipport']) if __name__ == '__main__':
url = 'http://www.xicidaili.com/nn/'
verify_url = "http://httpbin.org/"
url_list = [url + str(i) for i in range(1, 2)]
tmp = tempfile.TemporaryFile()
for url in url_list:
content = get_content(url)
time.sleep(2)
get_info(tmp, content) print('原始数据下载完毕,开始构建代理池...') tmp.seek(0)
ipports = [ item.decode('utf-8').strip().split(':') for item in tmp.readlines() ]
tmp.close() pool = ThreadPoolExecutor(20)
for ipport in ipports:
ip,port = ipport
v = pool.submit(verify_ip, ip, port, verify_url)
v.add_done_callback(callback)
pool.shutdown(wait=True) print('代理池构建完毕,共获得可用代理 {} 个'.format(len(ip2port)))
print(ip2port)
multiprocessing.dummy.Pool
import time
import requests
from lxml import etree
from requests.exceptions import RequestException
from multiprocessing.dummy import Pool as ThreadPool available_proxies = [] def get_one_page(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
}
reponse = requests.get(url, headers=headers)
if reponse.status_code == 200:
return reponse.text
return None
except RequestException:
return None def get_one_parse(url):
print('url: {}'.format(url))
ipports = []
html = get_one_page(url)
if html:
html = etree.HTML(html)
ips = html.xpath('.//*[@id="list"]/table/tbody//td[1]/text()')
ports = html.xpath('.//*[@id="list"]/table/tbody//td[2]/text()')
for (ip, port) in zip(ips, ports):
ipports.append('{}:{}'.format(ip, port))
ipports = list(set(ipports))
print('res: {}'.format(ipports))
return ipports
return None def fetch(all_proxies):
url = 'https://www.kuaidaili.com/free/intr/{}/'
for i in range(1, 61):
ret = get_one_parse(url.format(i))
if ret:
all_proxies.extend(ret)
time.sleep(1)
all_proxies = list(set(all_proxies))
print('爬取了前60页,去重后共获得{}个代理'.format(len(all_proxies))) def save():
with open('ip2port.txt', 'a+') as wf:
for item in available_proxies:
wf.write(item + '\n')
print('{}个可用代理保存完毕'.format(len(available_proxies))) def sub_verify(item):
proxy = {'http': 'http://{0}'.format(item)}
try:
response = requests.get("http://httpbin.org/", proxies=proxy, timeout=3)
if response.status_code == 200:
print("{} is ok".format(item))
available_proxies.append(item)
except Exception as e:
print("{} failed".format(item)) def verify(ipports):
print('开始验证可用代理...')
pool = ThreadPool(20)
pool.map(sub_verify, ipports)
print('验证完毕,共获取可用代理 {} 个'.format(len(available_proxies)))
save() if __name__ == "__main__":
all_proxies = []
fetch(all_proxies)
print(all_proxies,len(all_proxies))
ipports = list(map(lambda x: x.strip(), all_proxies))
verify(ipports)
建立爬虫代理IP池的更多相关文章
- 【python3】如何建立爬虫代理ip池
一.为什么需要建立爬虫代理ip池 在众多的网站防爬措施中,有一种是根据ip的访问频率进行限制的,在某段时间内,当某个ip的访问量达到一定的阀值时,该ip会被拉黑.在一段时间内被禁止访问. 这种时候,可 ...
- Python爬虫代理IP池
目录[-] 1.问题 2.代理池设计 3.代码模块 4.安装 5.使用 6.最后 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代 ...
- 维护爬虫代理IP池--采集并验证
任务分析 我们爬的免费代理来自于https://www.kuaidaili.com这个网站.用`requests`将ip地址与端口采集过来,将`IP`与`PORT`组合成`requests`需要的代理 ...
- 利用代理IP池(proxy pool)搭建免费ip代理和api
先看这里!!!---->转载:Python爬虫代理IP池(proxy pool) WIIN10安装中遇到的问题: 一.先安装Microsoft Visual C++ Compiler for P ...
- 如何建立自己的代理IP池,减少爬虫被封的几率
如何建立自己的代理IP池,减少爬虫被封的几率 在爬虫过程中,难免会遇到各种各样的反爬虫,运气不好,还会被对方网站给封了自己的IP,就访问不了对方的网站,爬虫也就凉凉. 代理参数-proxies 首先我 ...
- 构建一个给爬虫使用的代理IP池
做网络爬虫时,一般对代理IP的需求量比较大.因为在爬取网站信息的过程中,很多网站做了反爬虫策略,可能会对每个IP做频次控制.这样我们在爬取网站时就需要很多代理IP. 代理IP的获取,可以从以下几个途径 ...
- python多线程建立代理ip池
之前有写过用单线程建立代理ip池,但是大家很快就会发现,用单线程来一个个测试代理ip实在是太慢了,跑一次要很久才能结束,完全无法忍受.所以这篇文章就是换用多线程来建立ip池,会比用单线程快很多.之所以 ...
- python爬虫构建代理ip池抓取数据库的示例代码
爬虫的小伙伴,肯定经常遇到ip被封的情况,而现在网络上的代理ip免费的已经很难找了,那么现在就用python的requests库从爬取代理ip,创建一个ip代理池,以备使用. 本代码包括ip的爬取,检 ...
- 爬虫入门到放弃系列05:从程序模块设计到代理IP池
前言 上篇文章吧啦吧啦讲了一些有的没的,现在还是回到主题写点技术相关的.本篇文章作为基础爬虫知识的最后一篇,将以爬虫程序的模块设计来完结. 在我漫(liang)长(nian)的爬虫开发生涯中,我通常将 ...
随机推荐
- [hgoi#2019/3/21]NOIP&NOI赛后总结
前言 今天做的是是2010年提高组和NOI的题目,做过几道原题,但是还是爆炸了,我真的太弱了. t1-乌龟棋 https://www.luogu.org/problemnew/show/P1541 这 ...
- js-元素相关
获取元素方法一 可以使用内置对象document上的getElementById方法来获取页面上设置了id属性的元素,获取到的是一个html对象,然后将它赋值给一个变量,比如: <script ...
- cf455C Civilization (并查集)
并查集维护每个联通块的直径和最小的最大深度,每次连得时候连的肯定是最大深度最小的那两个点 #pragma GCC optimize(3) #include<bits/stdc++.h> # ...
- Learn to securely share files on the blockchain with IPFS!
https://medium.com/@mycoralhealth/learn-to-securely-share-files-on-the-blockchain-with-ipfs-219ee47d ...
- JBoss/Wildfly 配置SQLserver服务器
JBoss/Wildfly 配置SQLserver服务器 http://blog.csdn.net/haitaolang/article/details/60467118 wildfly standa ...
- C# Winfrom MDI(多文档界面)
1.首先设置父级Form1界面,只需要将该界面的IsMdiContainer属性设置为true: 2.设置按钮的事件来打开子级的窗口Form2,Form3等等: 3.在From1内设置一个容器pane ...
- plink: 等位型计数(allele count)
对genotype的等位型进行计数,需要用到以下参数: --freq Allele frequencies--counts Modifies --freq to report actual allel ...
- 2019-1-17 script(1)
伪终端(Pseudo Terminal)是成对的逻辑终端设备. grant 授予 tty是teletype(电传打字机)的缩写,后来便成了终端设备的代名词 虚拟终端pty(pseudo-tty) p ...
- 第二十二节,TensorFlow中的图片分类模型库slim的使用、数据集处理
Google在TensorFlow1.0,之后推出了一个叫slim的库,TF-slim是TensorFlow的一个新的轻量级的高级API接口.这个模块是在16年新推出的,其主要目的是来做所谓的“代码瘦 ...
- appium desktop 1.7 的swipe功能不能用,重写。
rt // @Override public void swipe(int startx,int starty,int endx,int endy,int ms){ Duration duration ...