# -*- coding: utf-8 -*-
# @Time : 2018/12/26 9:55 PM
# @Author : cxa
# @Software: PyCharm
import asyncio
import aiohttp
from db.mongohelper import save_data
import hashlib
import pathlib
import ujson
from logger.log import crawler
from utils import proxy_helper
from retrying import retry
from itertools import islice try:
import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
sem = asyncio.Semaphore(1000)
url = "https://xxx.xxx.com" @retry(stop_max_attempt_number=5)
def get_proxy():
proxy = proxy_helper.get_proxy()
host = proxy.get('ip')
port = proxy.get('port')
ip = f"http://{host}:{port}"
return ip async def fetch(item, session, proxy, retry_index=0):
try:
name = item
sf = get_md5(name)
data = {"kw": name, "signinfo": sf}
async with session.post(url, data=data, proxy=proxy, verify_ssl=False) as req:
res_status = req.status
if res_status == 200:
data = ujson.loads(await req.text())
searchdata = data.get("searchResult")
if searchdata:
await save_data(searchdata)
else:
crawler.info(f'<search_name: {name}>, data: {data},') except IndexError as e:
print(f"<出错时候的数据:{seq}>,<原因: e>")
except Exception as e:
data = None
crawler.error(f"<Error: {url} {str(e)}>")
if not data:
crawler.info(f'<Retry url: {url}>, Retry times: {retry_index+1}')
retry_index += 1
proxy = get_proxy()
return await fetch(item, session, proxy, retry_index) async def bound_fetch(item, session, proxy):
async with sem:
await fetch(item, session, proxy) async def print_when_done(tasks):
[await _ for _ in limited_as_completed(tasks, 2000)] async def run(data):
async with aiohttp.ClientSession() as session:
proxy = get_proxy()
coros = (asyncio.ensure_future(bound_fetch(item, session, proxy)) for item in data)
await print_when_done(coros) def limited_as_completed(coros, limit):
futures = [
asyncio.ensure_future(c)
for c in islice(coros, 0, limit)
] async def first_to_finish():
while True:
await asyncio.sleep(0.01)
for f in futures:
if f.done():
futures.remove(f)
try:
newf = next(coros)
futures.append(
asyncio.ensure_future(newf))
except StopIteration as e:
pass
return f.result() while len(futures) > 0:
yield first_to_finish() def get_use_list():
fname = pathlib.Path.joinpath(pathlib.Path.cwd(), "namelist.txt")
with open(fname, encoding='utf-8') as fs:
data = (i.strip() for i in fs.readlines())
return data def get_md5(key):
m = hashlib.md5()
m.update(f'{key}0jjj890j0369dce05f9'.encode('utf-8'))
a = m.hexdigest()
return a if __name__ == '__main__':
crawler.info("开始下载")
data = get_use_list()
loop = asyncio.get_event_loop()
loop.run_until_complete(run(data))
loop.close()

aiohttp分流处理的更多相关文章

  1. 【转】aiohttp 源码解析之 request 的处理过程

    [转自 太阳尚远的博客:http://blog.yeqianfeng.me/2016/04/01/python-yield-expression/] 使用过 python 的 aiohttp 第三方库 ...

  2. aiohttp使用队列

    获取百度的搜索结果,然后把百度的长链接,获取到真实的url import time import aiofiles import aiohttp import asyncio from lxml im ...

  3. aiohttp AppRunner的用法

    参考廖雪峰的aiohttp教程,会出现两个DeprecationWarning, loop argument is deprecated Application.make_handler(...) i ...

  4. python requests与aiohttp 速度对比

    环境:centos7 python3.6 测试网址:www.bai.com 测试方式:抓取百度100次 结果: aio: 10.702147483825684srequests: 12.4046785 ...

  5. 利用aiohttp制作异步爬虫

      asyncio可以实现单线程并发IO操作,是Python中常用的异步处理模块.关于asyncio模块的介绍,笔者会在后续的文章中加以介绍,本文将会讲述一个基于asyncio实现的HTTP框架--a ...

  6. aiohttp的笔记之TCPConnector

    TCPConnector维持链接池,限制并行连接的总量,当池满了,有请求退出再加入新请求.默认是100,limit=0的时候是无限制 1.use_dns_cache: 使用内部DNS映射缓存用以查询D ...

  7. Python中syncio和aiohttp

    CPython 解释器本身就不是线程安全的,因此有全局解释器锁(GIL),一次只允许使用一个线程执行 Python 字节码.因此,一个 Python 进程通常不能同时使用多个 CPU 核心.然而,标准 ...

  8. aiohttp文档翻译-server(一)

    web server 快速入门 运行一个简单的web server 为了实现web server, 首先需要实现request handler 一个 request handler 必须是一个coro ...

  9. python链家网高并发异步爬虫asyncio+aiohttp+aiomysql异步存入数据

    python链家网二手房异步IO爬虫,使用asyncio.aiohttp和aiomysql 很多小伙伴初学python时都会学习到爬虫,刚入门时会使用requests.urllib这些同步的库进行单线 ...

随机推荐

  1. 学习Spring Boot:(二十)使用 MongoDB

    前言 MongoDB 1 是可以应用于各种规模的企业.各个行业以及各类应用程序的开源数据库.基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案.Mongo ...

  2. Linux 系统缓存机制学习

    前言:本文为参考他人的文章,是一篇学习记录型博客.理解linux的系统缓存机制有助于理解elasticsearch实时更新的原理. 一.缓存机制 为了提高文件系统性能,内核利用一部分物理内存分配出缓冲 ...

  3. 「loj3057」「hnoi2019」校园旅行

    题目 一个n个点m条边的无向图,每个点有0 / 1 的标号; 有q个询问,每次询问(u,v)直接是否存在回文路径(可以经过重复的点和边); $1 \le n \le 5 \times 10^3  , ...

  4. shoi2017小结

    某省选 胡雨菲让我做的,她自己已经AK了... 在loj(自由oj?)上面搜索shoi2017即可. 洛谷上也有,搜六省联考就行 第一题:大水题枚举 P3745 看题目就很水:(其实是因为胡雨菲给我讲 ...

  5. std::lock_guard和std::unique_lock

    std::unique_lock也可以提供自动加锁.解锁功能,比std::lock_guard更加灵活 https://www.cnblogs.com/xudong-bupt/p/9194394.ht ...

  6. 预测氨基酸替换的致病性及分子机制:MutPred工具的使用

    MutPred的功能是预测氨基酸替换后的致病性及其分子机制,旧版本见链接:http://mutpred1.mutdb.org/ 新版本更新为MutPred2,见网站链接:http://mutpred2 ...

  7. #ifndef HeaderName_h #define HeaderName_h #endif 使用详解

    想必很多人都看到过头文件中写有:#ifndef HeaderName_h                                                #define HeaderNa ...

  8. @RequestBody

    之前写过一篇记录文章,写的是将一个比较复杂的数据结构在前台组合起来后传递到后台. 当时并不太了解@RequestBody,也并没有使用js提供的JSON.stringify()方法 所有都是自己写的, ...

  9. LVS+keepalived 的DR模式的两种做法

    LVS DR模式搭建 准备工作 三台机器: dr:192.168.13.15 rs1:192.168.13.16 rs2: 192.168.13.17 vip:192.168.13.100 修改DR上 ...

  10. keepalive的工作原理和如何做到健康检查

    keepalived是以VRRP协议为实现基础的,VRRP全称Virtual Router Redundancy Protocol,即虚拟路由冗余协议. 虚拟路由冗余协议,可以认为是实现路由器高可用的 ...