# -*- 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. Android应用程序签名详解

    http://blog.csdn.net/lyq8479/article/details/6401093 本文主要讲解Android应用程序签名相关的理论知识,包括:什么是签名.为什么要给应用程序签名 ...

  2. Spring的后置处理器BeanFactoryPostProcessor

    新建一个JavaBean UserBeanFactoryPostProcessor 实现了BeanFactoryPostProcessor接口 Spring配置文件如下: 编写测试用例 从结果可以看出 ...

  3. 【洛谷P3586】LOG

    题目大意:维护一个集合,支持单点修改.查询小于 X 的数的个数.查询小于 X 的数的和. 题解:学习到了动态开点线段树.对于一棵未经离散化的权值线段树来说,对于静态开点来说,过大的值域会导致不能承受的 ...

  4. 【codevs4919】线段树练习4

    题目大意:维护一个长度为 N 的序列,支持两种操作:区间加,区间查询有多少数是 7 的倍数. 题解:在每个线段树中维护一个权值数组 [0,6],由于个数显然支持区间可加性,因此可用线段树来维护. 代码 ...

  5. table默认的box-sizing在不同浏览器不同

    转载自:https://blog.csdn.net/csm0912/article/details/88290672

  6. 附录B. Spring Boot 配置文件application.properties

    #SPRING CONFIG (ConfigFileApplicationListener) spring.config.name= # config file name (default to 'a ...

  7. 史上最全 40 道 Dubbo 面试题及答案

    https://blog.csdn.net/zl1zl2zl3/article/details/83721147

  8. WebAPI跨域处理

    原文来自:http://www.cnblogs.com/heifengwll/p/6243374.html WebApi2跨域问题   一.跨域问题产生的原因:同源策略(Same origin pol ...

  9. Java之Jacob调用COM接口DLL-----------------------------------dm。dll

    用Java控制windows了,嗯,低层次按键模拟,可控制游戏,内存也不在话下. 一.环境介绍 1.myeclipse8.5 2.著名按键插件dm.dll  32bit.此插件实现COM接口,百度百科 ...

  10. C# 部分类使用partial修饰

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace pati ...