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. Spring切面编程Aspect之@Before和@Around用法

    查看dao层使用的sql import java.util.Arrays; import org.apache.commons.lang.ArrayUtils; import org.aspectj. ...

  2. vscode 显示 Module 'turtle' has no … member

    初次运行与 turtle 相关的 Python 代码时,vscode 上显示 Module 'turtle' has no - member. 这时,我们可以在 vscode 的设置里添加如下代码: ...

  3. pycharm 报错 ModuleNotFoundError: No module named 'distutils.core'

    之气的虚拟机不好使了,重新装了最新版本,安装了ubuntu18.4,然后安装pycharm,但新建项目的时候报错: ModuleNotFoundError: No module named 'dist ...

  4. nodeJS中使用mongoose模块操作mongodb数据库

    在实际运用中,对于数据库的操作我们不可能一直在cmd命令行中进行操作,一般情况下需要在node环境中来操作mongodb数据库,这时就需要引入mongoose模块来对数据库进行增删改查等操作. 首先, ...

  5. ES6模块化及优点,简单案例让你秒懂

    模块化:模块是一个文件     好处:         1.减少命名冲突         2.避免引入时的层层依赖         3.可以提升执行效率     **第一种方法************ ...

  6. 在eclipse导入项目的步骤

    1. Import 2. Next 3. 确定  选中copy projects into workspace    Finish 这样项目就导入进来了. 4.导入jar包 Configure Bui ...

  7. Jupyter安装和环境配置

    配置: 1. 命令行启动 jupyter notebook 2. 也可以Anaconda直接启动 3. 设置token,如下图所示,命令行中输入 jupyter notebook list C:\Us ...

  8. Hadoop_22_MapReduce map端join实现方式解决数据倾斜(DistributedCache)

    1.Map端Join解决数据倾斜   1.Mapreduce中会将map输出的kv对,按照相同key分组(调用getPartition),然后分发给不同的reducetask 2.Map输出结果的时候 ...

  9. Protocol handler start failedCaused by: java.net.SocketException: Permission denied

    最近在使用mac启动项目的时候,发现原本在Windows下正常跑的项目报错如下: Protocol handler start failedCaused by: java.net.SocketExce ...

  10. 服务器上的UID按钮

    定位用的,比如你机柜上有很多台机器,你在前面按下UID灯,机器后面也有一个UID灯会亮起来,这样当你到后面去的时候你就知道刚才在前面看的是哪一台,另外,有人通过ILO远程端口连接到你的服务器的时候,U ...