import asyncio
import aiohttp
import async_timeout
from lxml import html
from timeit import default_timer as timer from db import DBData class Crawler:
def __init__(self, **kwargs):
self.domains = kwargs["domains"]
self.max_depth = kwargs["max_depth"]
self.max_retries = 3
self.max_workers = 10
self.Q = asyncio.Queue()
self.db_Q = asyncio.Queue()
self.cache = set()
self.count = 0
self.loop = asyncio.get_event_loop()
self.db_data = DBData() # Clear
self.db_data.clear_crawler() async def get(self, url, timeout):
with async_timeout.timeout(timeout):
async with self.session.get(url) as response:
return await response.text() async def extract_urls(self, url, timeout=10):
tree = html.fromstring(await self.get(url, timeout))
# Search only in domains
return {p for p in tree.xpath("//a/@href")}
# if any(domain in p for domain in self.domains)} async def worker(self):
while True:
url, depth, retries = await self.Q.get()
if url in self.cache:
self.db_Q.put_nowait(url)
self.Q.task_done()
continue
try:
new_urls = await self.extract_urls(url)
except Exception as e:
if retries <= self.max_retries:
self.Q.put_nowait((url, depth, retries + 1))
else:
print("Error in %s: %s" % (url, repr(e)))
else:
self.cache.add(url)
self.count += 1
self.db_Q.put_nowait(url)
print("Depth: %s Retry: %s Visited: %s" % (depth, retries, url))
if depth+1 <= self.max_depth:
for x in new_urls:
self.Q.put_nowait((x, depth + 1, retries))
self.Q.task_done() async def run(self):
async with aiohttp.ClientSession(loop=self.loop) as session:
self.session = session
workers = [self.worker() for _ in range(self.max_workers)]
workers += [self.write_to_db() for _ in range(self.max_workers)]
tasks = [self.loop.create_task(x) for x in workers]
await asyncio.sleep(5)
await self.Q.join()
await self.db_Q.join()
for task in tasks:
task.cancel() def start(self):
for domain in self.domains:
print("Crawling %s start..." % domain) self.Q.put_nowait((domain, 0, 0))
start_time = timer()
self.loop.run_until_complete(asyncio.gather(self.run()))
self.loop.close()
runtime = timer() - start_time print("Crawling %s end. Exec time: %s. Requests: %s" % (
domain, runtime, self.count)) async def write_to_db(self):
while True:
address = await self.db_Q.get()
if await self.db_data.check_url(address) is None:
self.db_data.add_url(address)
print("Write to DB: %s" % address)
self.db_Q.task_done() if __name__ == "__main__":
options = {
"domains": ["https://www.yahoo.com/news/"],
"max_depth": 1
}
c = Crawler(**options)
c.start()

aiohttp爬虫的模板,类的形式的更多相关文章

  1. C++模板类的使用

    1.定义模板类 通过类似于下面的语法可以定义一个模板类: template<typename T> class Job : public virtual RefBase { public: ...

  2. C++:类模板与模板类

    6.3 类模板和模板类 所谓类模板,实际上是建立一个通用类,其数据成员.成员函数的返回值类型和形参类型不具体指定,用一个虚拟的类型来代表.使用类模板定义对象时,系统会实参的类型来取代类模板中虚拟类型从 ...

  3. C++ 模板类解析

    具体模板类作用这边就不细说了,下面主要是描述下模板类的使用方法以及注意的一些东西. #include <iostream> using namespace std; template &l ...

  4. 使用模板类导致error LNK2019: 无法解析的外部符号

    原地址 1.定义模板类: template<class T> class Stack {....}; 2.定义模板成员函数: 每个函数头都要以相同的模板声明打头,并将类限定符改成:类名&l ...

  5. 开涛spring3(7.2) - 对JDBC的支持 之 7.2 JDBC模板类

    7.2  JDBC模板类 7.2.1  概述 Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,所以其他模板类都是基于它封装完成的,JDB ...

  6. 7.2 C++模板类实例化

    参考:http://www.weixueyuan.net/view/6399.html 总结: array < int >表明用int类型来代替模板类中的类参数“T”,编译器会将模板类ar ...

  7. [C++]模板类和模板函数

    参考: C++ 中模板使用详解 C++模板详解 概念 为了避免因重载函数定义不全面而带来的调用错误,引入了模板机制 定义 模板是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模 ...

  8. (转)JDBC模板类。

    Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,所以其他模板类都是基于它封装完成的,JDBC模板类是第一种工作模式. JdbcTempl ...

  9. spring3:对JDBC的支持 之 JDBC模板类

    7.2  JDBC模板类 7.2.1  概述 Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,所以其他模板类都是基于它封装完成的,JDB ...

随机推荐

  1. 将eChart图片利用POI导出到Excel

    在使用POI进行将数据导出到Excel时, 若要将eChart在前端生成的统计图(如柱状图.折线图.饼图等)一并导出,使用POI在后台构建数据图比较复杂,因此我选择将eChart在前端的统计图的bas ...

  2. SVN合并时报错:合并跟踪不允许丢失子树Merge tracking not allowed with missing subtrees; try restoring these items

    使用的是TortoiseSVN; Merge tracking not allowed with missing subtrees; try restoring these items 下面会有跟着几 ...

  3. 按钮在执行frame动画的时候怎么响应触发事件?

    按钮在执行frame动画的时候怎么响应触发事件? 代码中效果(请注意,我并没有点击到按钮,而是点击到按钮的终点frame值处): 对应的代码: // // ViewController.m // Ta ...

  4. 乘风破浪:LeetCode真题_015_3Sum

    乘风破浪:LeetCode真题_015_3Sum 一.前言 关于集合的操作,也是编程最容易考试的问题,比如求集和中的3个元素使得它们的和为0,并且要求不重复出现,这样的问题该怎么样解决呢? 二.3Su ...

  5. 沉淀再出发:再谈java的多线程机制

    沉淀再出发:再谈java的多线程机制 一.前言 自从我们学习了操作系统之后,对于其中的线程和进程就有了非常深刻的理解,但是,我们可能在C,C++语言之中尝试过这些机制,并且做过相应的实验,但是对于ja ...

  6. POJ | Boolean Expressions

    总时间限制: 1000ms  内存限制: 65536kB 描述The objective of the program you are going to produce is to evaluate ...

  7. Codeforces Round #441 (Div. 2)【A、B、C、D】

    Codeforces Round #441 (Div. 2) codeforces 876 A. Trip For Meal(水题) 题意:R.O.E三点互连,给出任意两点间距离,你在R点,每次只能去 ...

  8. GPU性能:光栅化、图层混合、离屏渲染

    So, shouldRasterize will not affect the green/red you see using Instruments. In order to have everyt ...

  9. wireshark:no interface can be used for capturing in this system with the current configuration

    在虚拟机unbuntu中,进行wireshark抓包,出现:no interface can be used for capturing in this system with the current ...

  10. Kali-linux Gerix Wifi Cracker破解无线网络

    Gerix Wifi Cracker是另一个aircrack图形用户界面的无线网络破解工具.本节将介绍使用该工具破解无线网络及创建假的接入点. 9.3.1 Gerix破解WEP加密的无线网络 在前面介 ...