async for 在爬虫中的使用例子
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 在爬虫中的使用例子的更多相关文章
- 跟着太白老师学python day11 闭包 及在爬虫中的基本使用
闭包的基本概念: 闭包 内层函数对外层函数的变量(不包括全局变量)的引用,并返回,这样就形成了闭包 闭包的作用:当程序执行时,遇到了函数执行,它会在内存中开辟一个空间,如果这个函数内部形成了闭包, 那 ...
- 深入理解协程(四):async/await异步爬虫实战
本文目录: 同步方式爬取博客标题 async/await异步爬取博客标题 本片为深入理解协程系列文章的补充. 你将会在从本文中了解到:async/await如何运用的实际的爬虫中. 案例 从CSDN上 ...
- asyncio在爬虫中的使用
# -*- coding: utf-8 -*- # 协程基础.py import asyncio import time async def request(url): print("正在请 ...
- 采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET
采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET undefined
- break在switch中的使用例子
/* Name:break在switch中的使用例子 Copyright: By.不懂网络 Author: Yangbin Date:2014年2月21日 03:16:52 Description:以 ...
- crawler_网络爬虫中编码的正确处理与乱码的解决策略
转载: http://hi.baidu.com/erliang20088/item/9156132bdaeae8949c63d134 最近一个月一直在对nutch1.6版进行中等层次的二次开发,本来是 ...
- [Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子
[Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子 sqlContext = HiveContext(sc) peopleDF = sqlContext. ...
- 【转】C# Async/Await 异步编程中的最佳做法
Async/Await 异步编程中的最佳做法 Stephen Cleary 近日来,涌现了许多关于 Microsoft .NET Framework 4.5 中新增了对 async 和 await 支 ...
- (二)Hadoop例子——运行example中的wordCount例子
Hadoop例子——运行example中的wordCount例子 一. 需求说明 单词计数是最简单也是最能体现MapReduce思想的程序之一,可以称为 MapReduce版"Hello ...
随机推荐
- H-ui前端框架,后端模板
http://www.h-ui.net/ H-ui前端框架系统是基于 HTML.CSS.JAVASCRIPT开发的轻量级web前端框架. H-ui是根据中国现阶段网站特性和程序员开发习惯,在boots ...
- caffe prototxt分析
测试用prototxt name: "CIFAR10_quick"layer { name: "data" type: "MemoryData&quo ...
- VisualVM的使用
1.解压压缩包(如visualvm143.zip) 2.修改etc/visualvm.conf 中的visualvm_jdkhome配置 3.双击bin/visualvm.exe 4.安装插件,可能一 ...
- ADF简单介绍
1.ADF也是用的MVC的分层模式,如下图所示 2.Model层代理数据服务将数据关联在View层,用户则是在View层的UI界面上的操作来更改Model层代理的数据,Controller控制层执行用 ...
- ASE2019 model组 事后诸葛亮会议记录
诸葛亮文档 设想和目标 1. 我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的描述? 传统编程教育模式下,初学者(主要是刚刚接触编程的学生)往往依靠老师与助教的课堂教学,由 ...
- Android之Json
Servlet部分 public class JasonAction extends HttpServlet { private JsonService service; public void do ...
- USC-- compute shader ps vs
http://cdn.imgtec.com/sdk-documentation/PowerVR%20Compute%20Development%20Recommendations.pdf powerV ...
- Codeforces Round #586 (Div. 1 + Div. 2) B. Multiplication Table
链接: https://codeforces.com/contest/1220/problem/B 题意: Sasha grew up and went to first grade. To cele ...
- 【细谈Java并发】谈谈LinkedBlockingQueue(转)
最近在看concurrent包的知识,看到LinkedBlockingQueue,发现一篇好文推荐给大家.原文地址:[细谈Java并发]谈谈LinkedBlockingQueue 1.简介 上篇我们介 ...
- 6、DockerFile解析:三步走、保留字指令
1.dockerfiel是什么 1.是什么 Dockerfile是用来构建Docker镜像的构建文件,是由一系列命令和参数构成的脚本. 2.构建三步骤 编写Dockerfile文件 docker bu ...