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. Attribute自定义特性+Asp.net MVC中的filter详解

    转载自:http://blog.csdn.net/wangyy130/article/details/44241957 一.filter简介 在了解自定义特性前,先引入一个概念filter,它是MVC ...

  2. JSP读取properties文件变量

    1.jsp代码 <%ResourceBundle res = ResourceBundle.getBundle("properties文件名"); %> 2.js代码 ...

  3. Springboot+mybatis+druid 配置多数据源

    项目结构 application.yml配置文件 spring: application: name: service datasource: primary: jdbc-url: jdbc:orac ...

  4. Centos7--从最小化系统发开发环境

    Centos7--从最小化系统发开发环境 ​程序员总是离不开"环境"的困扰,从进入新手村的那一天就开始手动搞各种环境.虽然阿里云学生服务很方便,但是想弄集群真的买不起.正好实验室有 ...

  5. NET如何使用ELinq-实现增删改查

    1 通过对ELinq主页的参考和学习,以及在项目中(wpf项目中用到的)中应用,ORM框架中的ELinq确实非常的强大,特此以建立wpf项目为例子来总结下如何在项目中应用ELinq,要想使用这个框架首 ...

  6. JAVA实现QQ聊天气泡

    最近做了聊天气泡功能,为自己的聊天室美化了一下聊天效果: 先来看一下效果: 主要的思路是:以一个JTextPane作为显示的面板,然后自定义一个组件JBubble气泡组件来实现他的聊天气泡,然后通过J ...

  7. RabbitMQ的特点与应用场景(二)

      1.RabbitMQ的主要特点 (1)可靠性:RabbitMQ可通过队列持久化,交换机持久化,消息持久化及ACK回应等机制保证可靠性 (2)支持多种语言与协议:RabbitMQ几乎支持所有的编程语 ...

  8. ES查询语句

    记录常用的es 查询 聚合 GET _cat / indices GET / p_ext_develop / _mapping / g GET / p_ext_develop / _analyze { ...

  9. linux在菜单中添加SEG选项

  10. linux——实际工作中如何使用linux

    实际工作中,linux系统都不会在我们自己的电脑上,linux系统安装在机房的服务器上,我们操作linux不可能跑到机房去,所以我们需要有一个工具,能在公司通过网络远程连接到机房的linux服务器上 ...