使用redis 、 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):
"""
定义一个枚举类, 继承了Enum, unique的意思是里面列举的对象的值是不能重复的
0 代表空闲状态 1 带表处于工作状态
"""
IDLE = 0
WORKING = 1
def decode_page(page_bytes, charsets=('utf-8',)):
"""
解码专用
:param page_bytes: 要解码的页面
:param charsets: 解码的方式
:return: 返回解析后的页面
"""
page_html = None
for charset in charsets:
try:
page_html = page_bytes.decode(charset)
break
except UnicodeDecodeError:
pass
return page_html
class Retry(object):
"""
定义一个包装器 用来装饰爬虫爬取页面 失败时尝试的次数 和 两次之间间隔的时间
"""
def __init__(self, *, retry_times=3,
wait_secs=5, errors=(Exception, )):
"""
把传入的参数赋给对象的属性,初始化赋值
:param retry_times: 尝试的次数
:param wait_secs: 间隔对的时间
:param errors: 异常种类
"""
self.retry_times = retry_times
self.wait_secs = wait_secs
self.errors = errors
def __call__(self, fn):
"""
call的作用是把对象变成函数, 装饰器都是函数, 这里可以用Retry() 里面可以传入参数的用来修改
尝试的次数和间隔的时间
:param fn: 所有的装饰器装饰的函数,在包装器中都用fn代替
:return: 返回包装器
"""
def wrapper(*args, **kwargs):
"""
包装器
:param args:可变参数
:param kwargs: 多个参数
:return: 返回函数
"""
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):
"""
抓取页面
:param current_url: 当前的url 要进行爬取的url
:param charsets:编解码的方式
:param user_agent:用户代理, 需要冒充有名的爬虫才可以爬取, 大多数网站是禁用不知名的爬虫的
:param proxies:
:return:返回爬取出来的页面
"""
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'):
"""
解析页面 获得页面中自己想要的内容
:param html_page: 解码之后的页面
:param domain: 域名 像www.baidu.com 就是一个域名
:return: 返回解析出来的东西
"""
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
class SpiderThread(Thread):
"""
多线程类
"""
def __init__(self, name, spider):
"""
daemon设为守护线程 name=name 是为了在爬虫中通过current_thread对象获取当前线程的名字
:param name: 线程的名字
:param spider: 线程要执行的爬虫
"""
super().__init__(name=name, daemon=True)
self.spider = spider
def run(self):
while True:
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
current_url = current_url.decode('utf-8')
if not redis_client.sismember('visited_urls', current_url):
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}):
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):
"""
判断进程中的爬虫状态是否活着
:param spider_threads:
:return: 如果有一个活着, 就返回真
"""
return any([spider_thread.spider.status == SpiderStatus.WORKING
for spider_thread in spider_threads])
redis_client = redis.Redis(host='112.74.171.100',
port=6379, password='940211')
mongo_client = pymongo.MongoClient(host='112.74.171.100', port=27017)
db = mongo_client.msohu
sohu_data_coll = db.webpages
hasher_proto = sha1()
def main():
"""
上面写的那么欢快,都是铺垫, 只有在这里面调用了才会执行
:return:
"""
if not redis_client.exists('m_sohu_task'):
redis_client.rpush('m_sohu_task', 'http://m.sohu.com/')
spider_threads = [SpiderThread('thread-%d' % i, Spider())
for i in range(10)]
for spider_thread in spider_threads:
spider_thread.start()
while redis_client.exists('m_sohu_task') or is_any_alive(spider_threads):
pass
print('Over!')
if __name__ == '__main__':
main()