Tornado5.11官方文档翻译(4)-用户手册-Queue示例 - 一个并发的网络爬虫

导航

用户指南

Queue示例 - 一个并发的网络爬虫

Tornado的tornado.queues模块为协程实现异步生产者/消费者模式,类似于Python标准库的队列模块为线程实现的模式。 一个yieldQueue.get的协程直到队列中有元素之前都会暂停。如果队列设置了最大容量,一个yieldQueue.put的协程在队列有空间之前都会暂停。 一个Queue维护一个从零开始的未完成任务的计数。put增加计数; task_done减少计数。 在此处的web-spider示例中,队列开始仅包含base_url。当一个worker获取一个页面时,它会解析链接并将新的链接放入队列中,然后调用task_done来减少一次计数器。 最终,一个worker获取一个之前URL已经被访问过的页面,并且队列中也没有剩余的工作。 因此,该worker对task_done的调用将计数器减少为零。 正在等待join的主协程将取消暂停然后结束。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python3

import time
from datetime import timedelta

from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag

from tornado import gen, httpclient, ioloop, queues

base_url = 'http://www.tornadoweb.org/en/stable/'
concurrency = 10


async def get_links_from_url(url):
"""Download the page at `url` and parse it for links.

Returned links have had the fragment after `#` removed, and have been made
absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes
'http://www.tornadoweb.org/en/stable/gen.html'.
"""
response = await httpclient.AsyncHTTPClient().fetch(url)
print('fetched %s' % url)

html = response.body.decode(errors='ignore')
return [urljoin(url, remove_fragment(new_url))
for new_url in get_links(html)]


def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url


def get_links(html):
class URLSeeker(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.urls = []

def handle_starttag(self, tag, attrs):
href = dict(attrs).get('href')
if href and tag == 'a':
self.urls.append(href)

url_seeker = URLSeeker()
url_seeker.feed(html)
return url_seeker.urls


async def main():
q = queues.Queue()
start = time.time()
fetching, fetched = set(), set()

async def fetch_url(current_url):
if current_url in fetching:
return

print('fetching %s' % current_url)
fetching.add(current_url)
urls = await get_links_from_url(current_url)
fetched.add(current_url)

for new_url in urls:
# Only follow links beneath the base URL
if new_url.startswith(base_url):
await q.put(new_url)

async def worker():
async for url in q:
if url is None:
return
try:
await fetch_url(url)
except Exception as e:
print('Exception: %s %s' % (e, url))
finally:
q.task_done()

await q.put(base_url)

# Start workers, then wait for the work queue to be empty.
workers = gen.multi([worker() for _ in range(concurrency)])
await q.join(timeout=timedelta(seconds=300))
assert fetching == fetched
print('Done in %d seconds, fetched %s URLs.' % (
time.time() - start, len(fetched)))

# Signal all the workers to exit.
for _ in range(concurrency):
await q.put(None)
await workers


if __name__ == '__main__':
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(main)

Tornado5.11官方文档翻译(4)-用户手册-Queue示例 - 一个并发的网络爬虫
https://www.shangyexin.com/2019/01/15/queue/
作者
Yasin
发布于
2019年1月15日
许可协议