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. WINAPI与CALLBACK

    #define WINAPI __stdcall #define CALLBACK __stdcall   都是__stdcall,无本质区别. CALLBACK只是为了告诉我们这是一个回调函数.

  2. SpringBoot的启动配置原理

    一.启动流程 创建SpringApplication对象 public class SpringApplication { public SpringApplication(Class... prim ...

  3. Spring注解实践

    原文:http://blog.csdn.net/xyh820/article/details/7303330 概述 注释配置相对于 XML 配置具有很多的优势: 它可以充分利用 Java 的反射机制获 ...

  4. Spring Cloud(八)高可用的分布式配置中心 Spring Cloud Config

    在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件.在Spring Cloud中,有分布式配置中心组件spring cloud config,它支持配 ...

  5. Python学习记录5-面向对象

    OOP 思想 以模块化思想解决工程问题 面向过程 vs 面向对象 由面向过程转向面向对象 常用名词 OO:面向对象 ooa:分析 ood:设计 oop:编程 ooI:实现 ooa -> ood ...

  6. liunx加载JX2410标准配置文件

  7. 【CQOI2017】老C的键盘

    Description https://loj.ac/problem/3023 一句话题意:给你一棵完全二叉树,每条边有一个方向,求这棵树有多少种不同的拓扑序. Solution 简化题意后,其实就是 ...

  8. MODI的OCR接口

    MODI的OCR接口 MODI的OCR接口 MODI的OCR接口

  9. axios 用 params/data 发送参数给 springboot controller,如何才能正确获取

    今天有人遇到接口调用不通的情况,粗略看了一下是axios跨域请求引起了.找到问题,处理就简单多了. 但是我看其代码,发现比较有意思 export function agentlist(query) { ...

  10. Linux文件系统之复制文件cp(文件复制)

    cp 命令(文件复制)   cp命令用来将一个或多个源文件或者目录复制到指定的目的文件或目录.它可以将单个源文件复制成一个指定文件名的具体的文件或一个已经存在的目录下.cp命令还支持同时复制多个文件, ...