webcrawler.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Recursive webcrawler example.
  2. For asynchronous DNS lookups install the `dnspython` package:
  3. $ pip install dnspython
  4. Requires the `pybloom` module for the bloom filter which is used
  5. to ensure a lower chance of recrawling an URL previously seen.
  6. Since the bloom filter is not shared, but only passed as an argument
  7. to each subtask, it would be much better to have this as a centralized
  8. service. Redis sets could also be a practical solution.
  9. A BloomFilter with a capacity of 100_000 members and an error rate
  10. of 0.001 is 2.8MB pickled, but if compressed with zlib it only takes
  11. up 2.9kB(!).
  12. We don't have to do compression manually, just set the tasks compression
  13. to "zlib", and the serializer to "pickle".
  14. """
  15. import re
  16. import time
  17. import urlparse
  18. from celery import task, group
  19. from eventlet import Timeout
  20. from eventlet.green import urllib2
  21. from pybloom import BloomFilter
  22. # http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
  23. url_regex = re.compile(
  24. r'\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))')
  25. def domain(url):
  26. """Returns the domain part of an URL."""
  27. return urlparse.urlsplit(url)[1].split(':')[0]
  28. @task(ignore_result=True, serializer='pickle', compression='zlib')
  29. def crawl(url, seen=None):
  30. print('crawling: {0}'.format(url))
  31. if not seen:
  32. seen = BloomFilter(capacity=50000, error_rate=0.0001)
  33. with Timeout(5, False):
  34. try:
  35. data = urllib2.urlopen(url).read()
  36. except (urllib2.HTTPError, IOError):
  37. return
  38. location = domain(url)
  39. wanted_urls = []
  40. for url_match in url_regex.finditer(data):
  41. url = url_match.group(0)
  42. # To not destroy the internet, we only fetch URLs on the same domain.
  43. if url not in seen and location in domain(url):
  44. wanted_urls.append(url)
  45. seen.add(url)
  46. subtasks = group(crawl.s(url, seen) for url in wanted_urls)
  47. subtasks.apply_async()