# -*- 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. SharePoint 2013 Newsfeed 没有出现的解决方法

    按照这个guide配置mysite: http://technet.microsoft.com/en-us/library/ee624362(v=office.15).aspx 但是newsfeed页 ...

  2. 并发容器——ConcurrentHashMap

    ConcurreentHashMap的实现原理与使用 ConcurrentHashMap是线程安全且高效的HashMap. 为什么要使用ConcurrentHashMap 在并发编程中使用HashMa ...

  3. Office2016自定义安装

    Office2016已经不提供自定义安装功能,而采用C2R安装方式.使用镜像安装时,默认全部安装.想要自定义安装就需要用到微软提供的Office2016部署工具. 步骤 下载并运行微软提供的Offic ...

  4. [hdu6148][Valley Numer]

    hdu6148 思路 一个数位dp模板题,注意判断前导0.用一个bz来记录当前是应该增还是可增可减.然后排除不满足条件的情况并进行dp即可. 代码 #include<cstdio> #in ...

  5. OpenCV 无法启动此程序,因为计算机中丢失opencv_core249.dll。请尝试重新安装改程序已解决此问题

    换了64位的系统,配置好之后运行之前的程序,竟然给我抛出这个错误.应该是我的opencv没有安装对吧.系统报错 无法启动此程序,因为计算机中丢失opencv_core249.dll.请尝试重新安装改程 ...

  6. 第2课:什么是SQL注入

    SQL注入:利用现有应用程序,将(恶意)的SQL命令注入到后台数据库引擎执行的能力,这是SQL注入的标准释义. 随着B/S模式被广泛的应用,用这种模式编写应用程序的程序员也越来越多,但由于开发人员的水 ...

  7. java代码示例(4)

    /** * 需求分析:计算100以内的和,用while * @author chenyanlong * 日期:2017/10/14 */ package com.hp.test04; public c ...

  8. javascript 字符串的连接和截取

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. java字符串转义,把&lt;&gt;转换成<>等字符【原】

    java字符串转义,把<>转换成<>等字符 使用的是commons-lang3-3.4 中的StringEscapeUtils类 package test; import ja ...

  10. Windows环境墙内搭建Go语言集成开发环境

    1 安装go环境 太简单略 2 安装vs code 找到微软的官方网站,下载Visual Studio Code,官网地址https://code.visualstudio.com/ 安装完成后进入V ...