面向对象的爬虫,程序更加优雅

爬取http://m.sohu.com的url 和页面

相关知识:,

  • python怎么用redis 数据库
  • python怎么用mongodb数据库
  • 装饰器
  • 多线程
import pickle
import zlib
from enum import Enum, unique
from hashlib import sha1
from random import random
from threading import Thread, current_thread
from time import sleep
from urllib.parse import urlparse

import pymongo
import redis
import requests
from bs4 import BeautifulSoup
from bson import Binary

# 创建一个类,用来存储爬虫的状态
@unique
class SpiderStatus(Enum):
    IDLE = 0
    WORKING = 1

# 解决爬下来的页面乱码的问题的对应的函数
def decode_page(page_bytes, charsets=('utf-8',)):
    page_html = None
    for charset in charsets:
        try:
            page_html = page_bytes.decode(charset)
            break
        except UnicodeDecodeError:
            pass
    return page_html

# 这是一个装饰器的类,retry_times表示重试的次数,wait_secs 表示等待的时间
class Retry(object):

    def __init__(self, *, retry_times=3,
                 wait_secs=5, errors=(Exception, )):
        self.retry_times = retry_times
        self.wait_secs = wait_secs
        self.errors = errors
    # 魔法方法(表示该方法可以直接调用)fn是传入的要装饰的函数
    def __call__(self, fn):

        def wrapper(*args, **kwargs):
            for _ in range(self.retry_times):
                try:
                    return fn(*args, **kwargs)
                except self.errors as e:
                    print(e)
                    sleep((random() + 1) * self.wait_secs)
            return None

        return wrapper

# 爬虫类
class Spider(object):

    def __init__(self):
        # 爬虫的属性是爬虫的状态
        self.status = SpiderStatus.IDLE

    # 抓取页面分方法
    @Retry()
    def fetch(self, current_url, *, charsets=('utf-8', ),
              user_agent=None, proxies=None):
        thread_name = current_thread().name
        print(f'[{thread_name}]: {current_url}')
        # 设置代理,如果没传入,默认为空
        headers = {'user-agent': user_agent} if user_agent else {}
        # 发出请求,得到服务器的返回对象
        resp = requests.get(current_url,
                            headers=headers, proxies=proxies)
        return decode_page(resp.content, charsets) \
            if resp.status_code == 200 else None

    # 分析页面的方法
    def parse(self, html_page, *, domain='m.sohu.com'):
        soup = BeautifulSoup(html_page, 'lxml')
        for a_tag in soup.body.select('a[href]'):
            parser = urlparse(a_tag.attrs['href'])
            scheme = parser.scheme or 'http'
            netloc = parser.netloc or domain
            if scheme != 'javascript' and netloc == domain:
                path = parser.path
                query = '?' + parser.query if parser.query else ''
                full_url = f'{scheme}://{netloc}{path}{query}'
                if not redis_client.sismember('visited_urls', full_url):
                    redis_client.rpush('m_sohu_task', full_url)

    def extract(self, html_page):
        pass

    def store(self, data_dict):
        pass

# 创建一个线程的对象,继承了Thread
class SpiderThread(Thread):
    # 传入体格 soider对象
    def __init__(self, name, spider):
        super().__init__(name=name, daemon=True)
        self.spider = spider

    def run(self):
        while True:
            #从redis里的列表里拿到url
            current_url = redis_client.lpop('m_sohu_task')
            # 如果没拿到就继续拿
            while not current_url:
                current_url = redis_client.lpop('m_sohu_task')
            # 把蜘蛛的状态设置为工作的状态    
            self.spider.status = SpiderStatus.WORKING
            # 设置url的编码
            current_url = current_url.decode('utf-8')
            #判断该url 是否访问过
            if not redis_client.sismember('visited_urls', current_url):
                # 把访问的url添加到redis里的集合里
                redis_client.sadd('visited_urls', current_url)
                # 调用 抓蜘蛛抓取页面的方法
                html_page = self.spider.fetch(current_url)
                # 判断得到的页面是否为空
                if html_page not in [None, '']:
                    hasher = hasher_proto.copy()
                    hasher.update(current_url.encode('utf-8'))
                    doc_id = hasher.hexdigest()
                    if not sohu_data_coll.find_one({'_id': doc_id}):
                        # 把得到的数据插入到mongodb数据库中
                        sohu_data_coll.insert_one({
                            '_id': doc_id,
                            'url': current_url,
                            'page': Binary(zlib.compress(pickle.dumps(html_page)))
                        })
                    self.spider.parse(html_page)
            self.spider.status = SpiderStatus.IDLE


def is_any_alive(spider_threads):
    return any([spider_thread.spider.status == SpiderStatus.WORKING
                for spider_thread in spider_threads])

# 创建一个连接redis的对象
redis_client = redis.Redis(host='39.108.188.19',
                           port=6379, password='lijin123')
# 创建一个Mongodb的连接对象
mongo_client = pymongo.MongoClient(host='39.108.188.19', port=27017)
# 创建mongodb数据库
db = mongo_client.msohu
# 创建一个集合
sohu_data_coll = db.webpages
hasher_proto = sha1()


def main():
    # 判断redis数据库里存不存在一个列表叫:m_sohu_task
    if not redis_client.exists('m_sohu_task'):
        # 不存在的 就添加url
        redis_client.rpush('m_sohu_task', 'http://m.sohu.com/')
    # 创建10个线程对象,并保存在一个列表中    
    spider_threads = [SpiderThread('thread-%d' % i, Spider())
                      for i in range(10)]
    # 循环这个列表,开启每个线程                  
    for spider_thread in spider_threads:
        spider_thread.start()
    # 如果 redis中的m_sohu_task的列表不为空(就是还有url还没爬取),或者 spider的状态还在工作。主线程就不能结束
    while redis_client.exists('m_sohu_task') or is_any_alive(spider_threads):
        pass

    print('Over!')


if __name__ == '__main__':
    main()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值