Python爬虫作业

Python爬虫 -- 美股吧多线程(二)

2017-06-10  本文已影响0人  chaosmind

目标

在大规模爬取数据前,先定一个能达到的小目标,比方说先爬个10万条数据。

爬虫爬数据太慢了,怎么爬快点?
程序中途中断了怎么办,好不容易爬了这么多数据,又要重头开始爬吗/(ㄒoㄒ)/
数据有重复的,占用多余的空间,影响统计怎么办?

这些都是刚开始爬取大规模数据都会遇到的问题,这次就来说说解决这些问题的思路。
涉及的知识点如下:

多线程的生产者和消费者模型

1. 单线程

2. 多线程

关于多线程知识的补充

如果对于线程的基础概念不了解的,可以看下参考链接,讲解十分到位。
廖雪峰 进程和线程
菜鸟教程 python多线程

多线程代码思路

前面的都是介绍偏概念的知识,估计耐心看的人不多,这里就讲讲代码中的思路

  1. 导入threading线程库,队列库Queue,python3的是queue。
  2. 创建任务队列,必须要设置队列的大小,否则队列中的任务数量会无限增长,占用大量内存。
task_queue = Queue.Queue(maxsize=thread_max_count*10)
  1. 创建生产者线程,threading.Thread(target=producer)需要传入线程要执行函数的名字,注意函数名不要加括号。调用start后,线程才会真正的跑起来。
"""负责对生产者线程的创建"""
def producer_manager():
    thread = threading.Thread(target=producer)
    thread.start()
  1. 生产者执行的生产任务
"""生产者负责请求网站首页,解析出每个帖子的url,和创建出帖子的请求任务并放入任务队列中"""
def producer():
    for title_page in range(start_page, total_page):
        text = request_title(title_page)
        if not text:
            continue
        tie_list = parse_title(text)
        for tie in tie_list:
            if tieba.find_one({'link':tie['link']}):             #数据去重的判断
                print('Data already exists: '+tie['link'])
            else:
                task_queue.put(tie)   #将任务放入队列
        log.update_one(run_log,{'$set':{'run_page':title_page}})  #记录断点数据
  1. 创建消费者线程。将线程放入list中放入方便管理。 调用task_queue.join(),表示若队列中还存在任务,那么主线程就阻塞住,不会往下面执行。
"""负责创建并管理消费者的线程"""
def consumer_manager():
    threads = []
    while len(threads) < thread_max_count:
        thread = threading.Thread(target=consumer)
        thread.setName("thread%d" % len(threads))
        threads.append(thread)
        thread.start()
    task_queue.join()

6.消费者执行的任务。这里用了一个while True做死循环,这样线程就不会结束,避免了创建和销毁线程带来的开销,能提高一点运行效率。任务执行完后需要调用queue.task_done()函数,告诉队列已经完成一个任务,只有所有任务都调用过queue.task_done()以后,队列才会解除阻塞,主线程继续往下执行。

"""消费者负责从任务队列中取出任务(即任务的消费),并执行爬取每篇帖子和里面评论的任务"""
def consumer():
    while True:
        if task_queue.qsize() == 0:
            time.sleep(3)
        else:
            task_count[0] = task_count[0] + 1
            #print("run time second %s, ready task counts %d, finish task counts %d, db counts %d"%(str(time.time() - start_time)[:6], task_queue.qsize(),task_count[0],tieba.count()))
            print("运行时间:%s秒,队列中剩余任务数%d,已完成任务数%d,数据已保存条数%d"%(str(time.time() - start_time)[:6], task_queue.qsize(),task_count[0],tieba.count()))
        tie = task_queue.get()
        request_comment(tie)
        insert_db(tie)
        task_queue.task_done()

断点记录和恢复

为了每次开始爬取数据不必重头开始,必须要记录下上次断点的位置

去重

运行结果

可以放在服务器上运行,抓取了10万条帖子的数据。我用个人电脑运行时,可能是因为网络或者路由器的问题,最多只能开5个线程,多了容易出现请求超时的情况,所以最后没办法只能放在服务器上去跑,速度挺快的,可以开20个线程,每秒能抓取十几个帖子,只不过cpu是瓶颈,一运行cpu就满载,想以后再考虑优化下吧。


数据库记录条数

完整代码

以下是python2.7版本的代码。
使用python3.6运行的话,import Queue要变成小写的import queue,还有用queue.Queue()来创建队列。

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import pymongo
import re, math
import time,sys
import threading
import Queue

thread_max_count = 20
total_page = 1501
db_name = 'tieba3'

"""若请求超时,则重试请求,重试次数在5次以内"""
def request(method, url, **kwargs):
    retry_count = 5
    while retry_count > 0:
        try:
            res = requests.get(url, **kwargs) if method == 'get' else requests.post(url, **kwargs)
            return res.text
        except:
            print('retry...', url)
            retry_count -= 1

"""请求网站的导航页,获取帖子数据"""
def request_title(title_page=1):
    title_url = "http://guba.eastmoney.com/list,cjpl_" + str(title_page) + ".html"
    return request('get', title_url, timeout=5)

"""解析导航页帖子的标题数据,包括阅读数,评论数,标题,作者,发布时间,评论的总页数"""
def parse_title(text):
    article_list = []
    soup = BeautifulSoup(text, 'lxml')
    host_url = 'http://guba.eastmoney.com'
    elem_article = soup.find_all(name='div', class_='articleh')
    for item in elem_article:
        article_dict = {'read_count': '', 'comment_count': '', 'page': '', 'title': '', 'tie': '', 'author': '',
                        'time': '', 'link': '', 'comment': ''}
        article_dict['read_count'] = item.select_one("span.l1").text
        article_dict['comment_count'] = item.select_one("span.l2").text
        article_dict['page'] = int(math.ceil(int(article_dict['comment_count']) / 30.0))
        article_dict['title'] = item.select_one("span.l3 > a").text
        article_dict['author'] = item.select_one("span.l4 > a").text if item.select_one("span.l4 > a") else u'匿名作者'
        article_dict['time'] = item.select_one("span.l5").text
        href = item.select_one("span.l3 > a").get("href")
        article_dict['link'] = host_url + href if href[:1] == '/' else host_url + '/' + href
        article_dict['comment'] = []
        article_list.append(article_dict)
    return article_list

"""根据评论的总页数,拼接出每一个评论页的url"""
def get_comment_urls(tie):
    comment_urls = []
    for cur_page in range(1, tie['page'] + 1 if tie['page'] > 0 else tie['page'] + 2):
        comment_url = tie['link'][:-5] + '_' + str(cur_page) + ".html"
        comment_urls.append(comment_url)
    return comment_urls

"""请求评论页的数据"""
def request_comment(tie):
    """跳过一些不是帖子的链接"""
    if re.compile(r'news,cjpl').search(tie['link']) == None:
        return

    print(tie['link']+' '+threading.currentThread().name)
    for comment_url in get_comment_urls(tie):
        text = request('get', comment_url, timeout=5)
        parse_comment(text, tie)

"""解析出评论页的数据,包括作者,时间,评论内容和计算评论楼层"""
def parse_comment(text, tie):
    soup = BeautifulSoup(text, 'lxml')
    if (soup.find(name='div', id='zw_body')):
        tie['tie'] = soup.find(name='div', id='zw_body').text.replace(u'\u3000', u'')
    div_list = soup.find(id="mainbody").find_all(name='div', class_="zwlitxt")
    for item in div_list:
        comment_info = {"author": '', "time": '', "content": '', "lou": 0}
        comment_info['author'] = item.find(name='span', class_="zwnick").text
        comment_info['lou'] = len(tie['comment']) + 1
        comment_info['time'] = item.find(name='div', class_="zwlitime").text[3:]
        if (item.find(name='div', class_="zwlitext stockcodec")):
            comment_info['content'] = item.find(name='div', class_="zwlitext stockcodec").text
            comment_info['content'] = u"没有评论内容" if comment_info['content'] == '' else comment_info['content']
        else:
            comment_info['content'] = u"没有评论内容"
        tie['comment'].append(comment_info)

"""消费者负责从任务队列中取出任务(即任务的消费),并执行爬取每篇帖子和里面评论的任务"""
def consumer():
    while True:
        if task_queue.qsize() == 0:
            time.sleep(3)
        else:
            task_count[0] = task_count[0] + 1
            #print("run time second %s, ready task counts %d, finish task counts %d, db counts %d"%(str(time.time() - start_time)[:6], task_queue.qsize(),task_count[0],tieba.count()))
            print("运行时间:%s秒,队列中剩余任务数%d,已完成任务数%d,数据已保存条数%d"%(str(time.time() - start_time)[:6], task_queue.qsize(),task_count[0],tieba.count()))
        tie = task_queue.get()
        request_comment(tie)
        insert_db(tie)
        task_queue.task_done()

"""负责创建并管理消费者的线程"""
def consumer_manager():
    threads = []
    while len(threads) < thread_max_count:
        thread = threading.Thread(target=consumer)
        thread.setName("thread%d" % len(threads))
        threads.append(thread)
        thread.start()
    task_queue.join()

"""数据保存"""
def insert_db(tie):
    tieba.insert_one(tie)

"""生产者负责请求网站首页,解析出每个帖子的url,和创建出帖子的请求任务并放入任务队列中"""
def producer():
    for title_page in range(start_page, total_page):
        text = request_title(title_page)
        if not text:
            continue
        tie_list = parse_title(text)
        for tie in tie_list:
            if tieba.find_one({'link':tie['link']}):             #数据去重的判断
                print('Data already exists: '+tie['link'])
            else:
                task_queue.put(tie)
        log.update_one(run_log,{'$set':{'run_page':title_page}})  #记录断点数据

"""负责对生产者线程的创建"""
def producer_manager():
    thread = threading.Thread(target=producer)
    thread.start()

if __name__ == '__main__':
    start_time = time.time()
    task_count = [0]
    client = pymongo.MongoClient('localhost', 27017)
    test = client['test']
    tieba = test[db_name]

    """
    创建一个log数据库,记录断点的位置,每次重新运行就从断点为位置重爬,
    这里记录的断点数据是帖子在首页的页数
    """
    log = test['log']
    run_log = {'db_name':db_name}
    if not log.find_one(run_log):
        log.insert_one(run_log)
        start_page = 1
    else:
        start_page = log.find_one(run_log)['run_page']
    print('start_page',start_page)

    """使用帖子的链接作为索引,可以提高去重时的查询效率"""
    tieba.create_index('link')
    """必须要设置队列的大小,否则队列中的任务数量会无限增长,占用大量内存"""
    task_queue = Queue.Queue(maxsize=thread_max_count*10)
    producer_manager() #创建生产者线程
    consumer_manager()  #创建消费者线程
上一篇 下一篇

猜你喜欢

热点阅读