Queue 示例 - 并发网络爬虫

Tornado 的 tornado.queues 模块(以及 asyncio 中非常相似的 Queue 类)为协程实现了异步生产者/消费者模式,类似于 Python 标准库的 queue 模块为线程实现的模式。

一个 yield Queue.get 的协程将在队列中有项目之前暂停。如果队列设置了最大大小,则 yield Queue.put 的协程将在有空间存放另一个项目之前暂停。

一个 Queue 保持一个未完成任务的计数,该计数从零开始。 put 会增加计数;task_done 会减少计数。

在下面的网络爬虫示例中,队列最初只包含 base_url。当一个工作进程获取页面时,它会解析链接并将新的链接放入队列中,然后调用 task_done 将计数器减少一次。最终,一个工作进程会获取一个页面,该页面所有的 URL 都已经被访问过,并且队列中也没有工作了。因此,该工作进程对 task_done 的调用会将计数器减少到零。正在等待 join 的主协程将被取消暂停并完成。

#!/usr/bin/env python3

import asyncio
import time
from datetime import timedelta

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

from tornado import gen, httpclient, queues

base_url = "https://tornado.pythonlang.cn/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
    'https://tornado.pythonlang.cn/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, dead = set(), 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))
                dead.add(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 | dead)
    print("Done in %d seconds, fetched %s URLs." % (time.time() - start, len(fetched)))
    print("Unable to fetch %s URLs." % len(dead))

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


if __name__ == "__main__":
    asyncio.run(main())