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