|
| 1 | +import pickle |
| 2 | +import zlib |
| 3 | +from enum import Enum, unique |
| 4 | +from hashlib import sha1 |
| 5 | +from random import random |
| 6 | +from threading import Thread, current_thread |
| 7 | +from time import sleep |
| 8 | +from urllib.parse import urlparse |
| 9 | + |
| 10 | +import pymongo |
| 11 | +import redis |
| 12 | +import requests |
| 13 | +from bs4 import BeautifulSoup |
| 14 | +from bson import Binary |
| 15 | + |
| 16 | + |
| 17 | +@unique |
| 18 | +class SpiderStatus(Enum): |
| 19 | + IDLE = 0 |
| 20 | + WORKING = 1 |
| 21 | + |
| 22 | + |
| 23 | +def decode_page(page_bytes, charsets=('utf-8',)): |
| 24 | + page_html = None |
| 25 | + for charset in charsets: |
| 26 | + try: |
| 27 | + page_html = page_bytes.decode(charset) |
| 28 | + break |
| 29 | + except UnicodeDecodeError: |
| 30 | + pass |
| 31 | + return page_html |
| 32 | + |
| 33 | + |
| 34 | +class Retry(object): |
| 35 | + |
| 36 | + def __init__(self, *, retry_times=3, |
| 37 | + wait_secs=5, errors=(Exception, )): |
| 38 | + self.retry_times = retry_times |
| 39 | + self.wait_secs = wait_secs |
| 40 | + self.errors = errors |
| 41 | + |
| 42 | + def __call__(self, fn): |
| 43 | + |
| 44 | + def wrapper(*args, **kwargs): |
| 45 | + for _ in range(self.retry_times): |
| 46 | + try: |
| 47 | + return fn(*args, **kwargs) |
| 48 | + except self.errors as e: |
| 49 | + print(e) |
| 50 | + sleep((random() + 1) * self.wait_secs) |
| 51 | + return None |
| 52 | + |
| 53 | + return wrapper |
| 54 | + |
| 55 | + |
| 56 | +class Spider(object): |
| 57 | + |
| 58 | + def __init__(self): |
| 59 | + self.status = SpiderStatus.IDLE |
| 60 | + |
| 61 | + @Retry() |
| 62 | + def fetch(self, current_url, *, charsets=('utf-8', ), |
| 63 | + user_agent=None, proxies=None): |
| 64 | + thread_name = current_thread().name |
| 65 | + print(f'[{thread_name}]: {current_url}') |
| 66 | + headers = {'user-agent': user_agent} if user_agent else {} |
| 67 | + resp = requests.get(current_url, |
| 68 | + headers=headers, proxies=proxies) |
| 69 | + return decode_page(resp.content, charsets) \ |
| 70 | + if resp.status_code == 200 else None |
| 71 | + |
| 72 | + def parse(self, html_page, *, domain='m.sohu.com'): |
| 73 | + soup = BeautifulSoup(html_page, 'lxml') |
| 74 | + for a_tag in soup.body.select('a[href]'): |
| 75 | + parser = urlparse(a_tag.attrs['href']) |
| 76 | + scheme = parser.scheme or 'http' |
| 77 | + netloc = parser.netloc or domain |
| 78 | + if scheme != 'javascript' and netloc == domain: |
| 79 | + path = parser.path |
| 80 | + query = '?' + parser.query if parser.query else '' |
| 81 | + full_url = f'{scheme}://{netloc}{path}{query}' |
| 82 | + if not redis_client.sismember('visited_urls', full_url): |
| 83 | + redis_client.rpush('m_sohu_task', full_url) |
| 84 | + |
| 85 | + def extract(self, html_page): |
| 86 | + pass |
| 87 | + |
| 88 | + def store(self, data_dict): |
| 89 | + pass |
| 90 | + |
| 91 | + |
| 92 | +class SpiderThread(Thread): |
| 93 | + |
| 94 | + def __init__(self, name, spider): |
| 95 | + super().__init__(name=name, daemon=True) |
| 96 | + self.spider = spider |
| 97 | + |
| 98 | + def run(self): |
| 99 | + while True: |
| 100 | + current_url = redis_client.lpop('m_sohu_task') |
| 101 | + while not current_url: |
| 102 | + current_url = redis_client.lpop('m_sohu_task') |
| 103 | + self.spider.status = SpiderStatus.WORKING |
| 104 | + current_url = current_url.decode('utf-8') |
| 105 | + if not redis_client.sismember('visited_urls', current_url): |
| 106 | + redis_client.sadd('visited_urls', current_url) |
| 107 | + html_page = self.spider.fetch(current_url) |
| 108 | + if html_page not in [None, '']: |
| 109 | + hasher = hasher_proto.copy() |
| 110 | + hasher.update(current_url.encode('utf-8')) |
| 111 | + doc_id = hasher.hexdigest() |
| 112 | + if not sohu_data_coll.find_one({'_id': doc_id}): |
| 113 | + sohu_data_coll.insert_one({ |
| 114 | + '_id': doc_id, |
| 115 | + 'url': current_url, |
| 116 | + 'page': Binary(zlib.compress(pickle.dumps(html_page))) |
| 117 | + }) |
| 118 | + self.spider.parse(html_page) |
| 119 | + self.spider.status = SpiderStatus.IDLE |
| 120 | + |
| 121 | + |
| 122 | +def is_any_alive(spider_threads): |
| 123 | + return any([spider_thread.spider.status == SpiderStatus.WORKING |
| 124 | + for spider_thread in spider_threads]) |
| 125 | + |
| 126 | + |
| 127 | +redis_client = redis.Redis(host='120.77.222.217', |
| 128 | + port=6379, password='1qaz2wsx') |
| 129 | +mongo_client = pymongo.MongoClient(host='120.77.222.217', port=27017) |
| 130 | +db = mongo_client.msohu |
| 131 | +sohu_data_coll = db.webpages |
| 132 | +hasher_proto = sha1() |
| 133 | + |
| 134 | + |
| 135 | +def main(): |
| 136 | + if not redis_client.exists('m_sohu_task'): |
| 137 | + redis_client.rpush('m_sohu_task', 'http://m.sohu.com/') |
| 138 | + spider_threads = [SpiderThread('thread-%d' % i, Spider()) |
| 139 | + for i in range(10)] |
| 140 | + for spider_thread in spider_threads: |
| 141 | + spider_thread.start() |
| 142 | + |
| 143 | + while redis_client.exists('m_sohu_task') or is_any_alive(spider_threads): |
| 144 | + pass |
| 145 | + |
| 146 | + print('Over!') |
| 147 | + |
| 148 | + |
| 149 | +if __name__ == '__main__': |
| 150 | + main() |
0 commit comments