import asyncio

import re

import typing

from concurrent.futures import Executor, ThreadPoolExecutor

from urllib.request import urlopen

DEFAULT_EXECUTOR = ThreadPoolExecutor(4)
ANCHOR_TAG_PATTERN = re.compile(b"<a.+?href=[\"|\'](.*?)[\"|\'].*?>", re.RegexFlag.MULTILINE | re.RegexFlag.IGNORECASE) async def wrap_async(generator: typing.Generator,
executor: Executor = DEFAULT_EXECUTOR,
sentinel=None,
*,
loop: asyncio.AbstractEventLoop = None):
"""
We wrap a generator and return an asynchronous generator instead
:param iterator:
:param executor:
:param sentinel:
:param loop:
:return:
""" if not loop:
loop = asyncio.get_running_loop() while True:
# 相当于执行next(generator)
result = await loop.run_in_executor(executor, next, generator, sentinel)
if result == sentinel:
# 如果链接为空跳出
break
yield result def follow(*links):
"""
:param links:
:return:
""" return ((link, urlopen(link).read()) for link in links) def get_links(text: str):
"""
Get back an iterator that gets us all the links in a text iteratively and safely
:param text:
:return:
""" # Always grab the last match, because that is how a smart http parser would interpret a malformed
# anchor tag
return (match.groups()[-1]
for match in ANCHOR_TAG_PATTERN.finditer(text)
# This portion is a safeguard against None matches and zero href matches
if hasattr(match, "groups") and len(match.groups())) async def main(*links):
async for current, body in wrap_async(follow(*links)):
print("Current url:", current)
print("Content:", body)
async for link in wrap_async(get_links(body)):
print(link) asyncio.run(main("https://www.cnblogs.com/c-x-a"))

async for 在爬虫中的使用例子的更多相关文章

  1. 跟着太白老师学python day11 闭包 及在爬虫中的基本使用

    闭包的基本概念: 闭包 内层函数对外层函数的变量(不包括全局变量)的引用,并返回,这样就形成了闭包 闭包的作用:当程序执行时,遇到了函数执行,它会在内存中开辟一个空间,如果这个函数内部形成了闭包, 那 ...

  2. 深入理解协程(四):async/await异步爬虫实战

    本文目录: 同步方式爬取博客标题 async/await异步爬取博客标题 本片为深入理解协程系列文章的补充. 你将会在从本文中了解到:async/await如何运用的实际的爬虫中. 案例 从CSDN上 ...

  3. asyncio在爬虫中的使用

    # -*- coding: utf-8 -*- # 协程基础.py import asyncio import time async def request(url): print("正在请 ...

  4. 采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET

    采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET undefined

  5. break在switch中的使用例子

    /* Name:break在switch中的使用例子 Copyright: By.不懂网络 Author: Yangbin Date:2014年2月21日 03:16:52 Description:以 ...

  6. crawler_网络爬虫中编码的正确处理与乱码的解决策略

    转载: http://hi.baidu.com/erliang20088/item/9156132bdaeae8949c63d134 最近一个月一直在对nutch1.6版进行中等层次的二次开发,本来是 ...

  7. [Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子

    [Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子 sqlContext = HiveContext(sc) peopleDF = sqlContext. ...

  8. 【转】C# Async/Await 异步编程中的最佳做法

    Async/Await 异步编程中的最佳做法 Stephen Cleary 近日来,涌现了许多关于 Microsoft .NET Framework 4.5 中新增了对 async 和 await 支 ...

  9. (二)Hadoop例子——运行example中的wordCount例子

    Hadoop例子——运行example中的wordCount例子 一.   需求说明 单词计数是最简单也是最能体现MapReduce思想的程序之一,可以称为 MapReduce版"Hello ...

随机推荐

  1. Lua虚拟机中的数据结构与栈

    Lua虚拟机中的数据结构与栈 来源 https://blog.csdn.net/zry112233/article/details/80828327 由上一篇文章可知解释器分析Lua文件之后生成Pro ...

  2. 【js】null 和 undefined的区别?

    1.首先看一个判断题:null和undefined 是否相等     console.log(null==undefined)//true     console.log(null===undefin ...

  3. 【opencv 源码剖析】 三、 morphOp 数学形态学滤波函数, 腐蚀和膨胀就是通过这个函数得到的

    // //_kernel : 形态学滤波的核 //anchor: 锚点再滤波核的位置 //iterations: 迭代次数 static void morphOp( int op, InputArra ...

  4. JS经典算法

     寻找500以内能被5和7整除的数字:for(var num=1;num<=500&&num++;) if(num%7==0&&num%5==0){ consol ...

  5. JAVA线程池例子

    用途及用法 网络请求通常有两种形式:第一种,请求不是很频繁,而且每次连接后会保持相当一段时间来读数据或者写数据,最后断开,如文件下载,网络流媒体等.另 一种形式是请求频繁,但是连接上以后读/写很少量的 ...

  6. Win10 通过附加进程调试时出现“此任务要求应用程序具有提升的权限”

    最近有新人在使用vs调试时出现了“此任务要求应用程序具有提升的权限”的提示,每次调试vs就会重启一次. 问到我时,我经过查了一番资料才给解决掉了. 其实,问题主要是因为直接启动vs项目时没有足够的权限 ...

  7. mysql主备搭建

    mysql主备搭建参考文档https://www.cnblogs.com/clsn/p/8150036.html前提条件:系统:Ubuntu 16.04.6 LTSMySQL版本:5.7.24主库IP ...

  8. linux物理地址和虚拟地址

  9. Django学习:连接Mysql数据库

    开发环境: Windows 10 Python 3.7.4 Django 2.2.6 Mysql 8.0.17 承接上一节:https://www.cnblogs.com/daydayupup/p/1 ...

  10. 《浏览器工作原理与实践》<07>变量提升:JavaScript代码是按顺序执行的吗?

    讲解完宏观视角下的浏览器后,从这篇文章开始,我们就进入下一个新的模块了,这里我会对 JavaScript 执行原理做深入介绍. 今天在该模块的第一篇文章,我们主要讲解执行上下文相关的内容.那为什么先讲 ...