webcrawler.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 a 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 requests
  17. from celery import task, group
  18. from eventlet import Timeout
  19. from pybloom import BloomFilter
  20. try:
  21. from urllib.parse import urlsplit
  22. except ImportError:
  23. from urlparse import urlsplit # noqa
  24. # http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
  25. url_regex = re.compile(
  26. r'\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))')
  27. def domain(url):
  28. """Return the domain part of a URL."""
  29. return urlsplit(url)[1].split(':')[0]
  30. @task(ignore_result=True, serializer='pickle', compression='zlib')
  31. def crawl(url, seen=None):
  32. print('crawling: {0}'.format(url))
  33. if not seen:
  34. seen = BloomFilter(capacity=50000, error_rate=0.0001)
  35. with Timeout(5, False):
  36. try:
  37. response = requests.get(url)
  38. except requests.exception.RequestError:
  39. return
  40. location = domain(url)
  41. wanted_urls = []
  42. for url_match in url_regex.finditer(response.text):
  43. url = url_match.group(0)
  44. # To not destroy the internet, we only fetch URLs on the same domain.
  45. if url not in seen and location in domain(url):
  46. wanted_urls.append(url)
  47. seen.add(url)
  48. subtasks = group(crawl.s(url, seen) for url in wanted_urls)
  49. subtasks.delay()