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 ...
随机推荐
- javascript中用&&跟||来简化if{}else{}的写法
原文:javascript中用&&跟||来简化if{}else{}的写法 目录 javascript中用&&跟||来简化if{}else{}的写法 1. if else ...
- MongoDB查询操作 返回指定字段(C#官方驱动)
首先,MongoDB中返回指定的字段的查询方法如下: db.person.find({Name:"小丑"},{Age:1,Sex:1}) 该语句表示:查询person表中name为 ...
- div可以同时设置背景图片和背景颜色吗?
前言 当然可以同时设置 当图片背景色不透明时 情况一:当图片的长.宽 >= div的长.宽时 我们最终看到div背景是图片,之所以说是最终看到,是因为在页面加载时,我们先看到的div背景是颜色, ...
- 4. Java入门程序
以eclipse为例,建立一个简单的Java程序. 首先启动eclipse,进入到如下主页面: 新建一个项目,选择“File-New-Java Project”: 弹出了一个如下页面,假设命名为Tes ...
- Tomat服务器学习
Tomat服务器学习 使用的是Redhat版本的Tomcat 目录结构 bin:可执行文件 conf:配置文件 lib:tomcat运行时依赖的jar包 logs:日志文件 temp:临时文件 web ...
- tomcat 的配置文件server.xml 几个端口的作用
tomcat中server.xml配置文件中几个port的作用和区别 在tomcat的server.xml中有这么几个port,很多人虽然一直在使用tomcat,但是却不知道这几个port各有什么作用 ...
- Centos7.7安装swoole
系统版本:centos 7.7(查看系统版本:cat /etc/redhat-release) 执行命令安装swoole: yum update -y && yum remove ph ...
- Python的Struct模块
python strtuct模块主要在Python中的值于C语言结构之间的转换.可用于处理存储在文件或网络连接(或其它来源)中的二进制数据. #!/usr/bin/env python # -*- c ...
- 8.JSP与JavaBean
1.<jsp:useBean> <html> <head> <title>jsp:useBean 标签的使用</title> </he ...
- PHP 求两个日期之间相差的天数、月数
<?php /** * 求两个日期之间相差的天数 * (针对1970年1月1日之后,求之前可以采用泰勒公式) * @param string $day1 * @param string $day ...