import aiohttp
import asyncio
import async_timeout
from urllib.parse import urljoin, urldefrag root_url = "http://python.org/"
crawled_urls, url_hub = [], [root_url, "%s/sitemap.xml" % (root_url), "%s/robots.txt" % (root_url)]
headers = {'user-agent': 'Opera/9.80 (X11; Linux x86_64; U; en) Presto/2.2.15 Version/10.10'} async def get_body(url):
async with aiohttp.ClientSession() as session:
try:
with async_timeout.timeout(10):
async with session.get(url, headers=headers) as response:
if response.status == 200:
html = await response.text()
return {'error': '', 'html': html}
else:
return {'error': response.status, 'html': ''}
except Exception as err:
return {'error': err, 'html': ''} async def handle_task(task_id, work_queue):
while not work_queue.empty():
queue_url = await work_queue.get()
if not queue_url in crawled_urls:
crawled_urls.append(queue_url)
body = await get_body(queue_url)
if not body['error']:
for new_url in get_urls(body['html']):
if root_url in new_url and not new_url in crawled_urls:
work_queue.put_nowait(new_url)
else:
print(f"Error: {body['error']} - {queue_url}") def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url def get_urls(html):
new_urls = [url.split('"')[0] for url in str(html).replace("'",'"').split('href="')[1:]]
return [urljoin(root_url, remove_fragment(new_url)) for new_url in new_urls] if __name__ == "__main__":
q = asyncio.Queue()
[q.put_nowait(url) for url in url_hub]
loop = asyncio.get_event_loop()
tasks = [handle_task(task_id, q) for task_id in range(3)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
for u in crawled_urls:
print(u)
print('-'*30)
print(len(crawled_urls))

  

asyncio Queue的使用例子的更多相关文章

  1. python中利用队列asyncio.Queue进行通讯详解

    python中利用队列asyncio.Queue进行通讯详解 本文主要给大家介绍了关于python用队列asyncio.Queue通讯的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细 ...

  2. threading包的例子和queue包的例子

    参考:https://www.cnblogs.com/tkqasn/p/5700281.html 参考:https://www.cnblogs.com/tkqasn/p/5700281.html th ...

  3. asyncio queue

    from asyncio import Queue,sleep import asyncio from threading import Thread import time qu=Queue() # ...

  4. rabbit的简单搭建,java使用rabbitmq queue的简单例子和一些坑

    一 整合 由于本人的码云太多太乱了,于是决定一个一个的整合到一个springboot项目里面. 附上自己的项目地址https://github.com/247292980/spring-boot 以整 ...

  5. python 多进程使用Queue通信的例子

    import time from multiprocessing import Process,Queue MSG_QUEUE = Queue(5) def startA(msgQueue): whi ...

  6. python异步编程模块asyncio学习(二)

    尽管asyncio应用通常作为单线程运行,不过仍被构建为并发应用.由于I/O以及其他外部事件的延迟和中断,每个协程或任务可能按一种不可预知的顺序执行.为了支持安全的并发执行,asyncio包含了thr ...

  7. 深入Asyncio(二)从线程到协程

    线程的真相 多线程并不是一无是处,在实际问题中,要权衡优劣势来选择多线程.多进程或是协程.协程为多线程的某些问题提供了一种解决方案,所以学习协程首先要对线程有一定了解. 多线程优点 代码可读性 多线程 ...

  8. 深入Asyncio(三)Asyncio初体验

    Asyncio初体验 Asyncio在Python中提供的API很复杂,其旨在替不同群体的人解决不同的问题,也正是由于这个原因,所以很难区分重点. 可以根据asyncio在Python中的特性,将其划 ...

  9. asyncio:python3未来并发编程主流、充满野心的模块

    介绍 asyncio是Python在3.5中正式引入的标准库,这是Python未来的并发编程的主流,非常重要的一个模块.有一个web框架叫sanic,就是基于asyncio,语法和flask类似,使用 ...

随机推荐

  1. svn 基础

    安装,略过. 快速创建.配置及启动项目 创建项目 svnadmin create /home/svn/project_name #创建名为project_name的项目(/home/svn为自定义创建 ...

  2. Kafka吞吐量测试案例

    Kafka吞吐量测试案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 领英公司参考连接:https://www.slideshare.net/JiangjieQin/produc ...

  3. 【转】C语言中的符号优先级

    转自: http://blog.csdn.net/huangblog/article/details/8271791 虽然在日常使用中,添加括号来明确规定运算符优先级是一种常识,但毕竟学校考试就喜欢考 ...

  4. 使用 highlight.js 在网页中高亮显示java 代码 【原】

    <html> <head> <meta charset="UTF-8"> <script src="http://apps.bd ...

  5. 【1】【leetcode-93】复原IP地址

    (不会,典型) 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式. 示例: 输入: "25525511135" 输出: ["255.255.11.135 ...

  6. navicat and connection is being used

    1.在已经保存的连接上上编辑,测试连接成功,但是点击连接就会一直提示 connection is being used 2.需要新建一个连接,才能使用,不能再已保存的上面修改

  7. [Android] Android RecycleView和ListView 自定义Adapter封装类

    在网上查看了很多对应 Android RecycleView和ListView 自定义Adapter封装类 的文章,主要存在几个问题: 一).网上代码一大抄,复制来复制去,大部分都运行不起来,或者 格 ...

  8. SpringBoot系列: Eclipse+Maven环境准备

    这个链接比我写得更全面, http://tengj.top/2018/01/01/maven/ =============================20190115补充: maven 的一些插件 ...

  9. Retrofit提交Json

    1.APIService为自定义接口类, 定义@Headers @Headers({"Content-Type: application/json","Accept: a ...

  10. vue-组件命名

    vue的组件命名,不能带有大写字母. 正确的写法: components:{ 'myder':av } 错误写法: components:{ 'myDer':av }