Query示例-并發(fā)網(wǎng)絡(luò)蜘蛛
Tornado 的tornado.queues模塊為協(xié)程實(shí)現(xiàn)了異步生產(chǎn)者/消費(fèi)者模式,類似于 Python 標(biāo)準(zhǔn)庫的queue模塊為線程實(shí)現(xiàn)的模式。
產(chǎn)生Queue.get暫停的協(xié)程直到隊(duì)列中有一個項(xiàng)目。如果隊(duì)列設(shè)置了最大大小,則產(chǎn)生的協(xié)程會Queue.put暫停,直到有空間容納另一個項(xiàng)目。
一個Queue維護(hù)未完成任務(wù)的計(jì)數(shù),該計(jì)數(shù)從零開始。 put增加計(jì)數(shù);task_done遞減它。
在此處的 web-spider 示例中,隊(duì)列開始時僅包含 base_url。當(dāng)工作人員獲取頁面時,它會解析鏈接并將新鏈接放入隊(duì)列中,然后調(diào)用task_done以減少計(jì)數(shù)器一次。最終,一個工作人員獲取了一個之前所有 URL 都已看到的頁面,并且隊(duì)列中也沒有剩余工作。因此,該工人的調(diào)用task_done 將計(jì)數(shù)器減至零。正在等待加入的主協(xié)同程序未暫停并完成。
#!/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, 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__":
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(main)
更多建議: