爬取小说2--协程间通信Python

通过Python进行协程间通信,大大加速爬取效率。

前言

是这样的,在之前的爬虫版本中,我们通过并发技术(python协程只是并发)。实现快速爬取小说的效果。
将速度提高为原来的几百倍了。但是却由于之前的多协程之间的通信,都是采用写入硬盘之后,再相互通信来实现的,所以,速度上还是存在一定的缺陷。

最新

在最新的版本中,我们采用多协程技术,采用在内存通信,这样来传递爬取的数据,之后,再来组合成为新的章节,这样就可以做到了对于之前版本的提速效果。而且需要代码量也下降了10行左右。

还是跟之前的版本一样目标小说网站只能是http://www.biquge.com.tw/这个网站下的小说的目录页

只要把目录页对应的小说的网址丢到main函数中的url里面,就可以实现了小说爬取。

小调整tips:
当然啦,根据自己的需求,可以试试看改改BuildGevent函数的step变量。这个表示每次发多少个协程。注意,最多是1200个。
这个设置,可以自己考虑,根据不同的设备情况,网络效果,对方服务器的稳定程度来进行判断。

import requests
import os
import gevent
from gevent import monkey
import random
import re
from lxml import etree
monkey.patch_all(select=False)
from urllib import parse
import time

IPs = [{'HTTPS': 'HTTPS://182.114.221.180:61202'},
       {'HTTPS': 'HTTPS://60.162.73.45:61202'},
       {'HTTPS': 'HTTPS://113.13.36.227:61202'},
       {'HTTPS': 'HTTPS://1.197.88.101:61202'}]
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cookie': '__cfduid=d820fcba1e8cf74caa407d320e0af6b5d1518500755; UM_distinctid=1618db2bfbb140-060057ff473277-4323461-e1000-1618db2bfbc1e4; CNZZDATA1272873873=2070014299-1518497311-https%253A%252F%252Fwww.baidu.com%252F%7C1520689081; yjs_id=5a4200a91c8aa5629ae0651227ea7fa2; ctrl_time=1; jieqiVisitTime=jieqiArticlesearchTime%3D1520693103'
}


def setDir():
    if 'Noval' not in os.listdir('./'):
        os.mkdir('./Noval')


def getNoval(url, id, data):
    while True:
        try:
            headers = HEADERS
            IP = random.choice(IPs)
            res = requests.get(url, headers=headers, proxies=IP)
            res.encoding = 'GB18030'
            html = res.text.replace(' ', ' ')  # 替换掉这个字符 换成空格~ 意思是一样的
            page = etree.HTML(html)
            content = page.xpath('//div[@id="content"]')
            ps = page.xpath('//div[@class="bookname"]/h1')
            if len(ps) != 0:
                s = ps[0].text + '\n'
                s = s + content[0].xpath("string(.)")
                data[id] = s
        except Exception:
            continue
        else:
            break


def getContentFile(url):
    headers = HEADERS
    IP = random.choice(IPs)
    res = requests.get(url, headers=headers, proxies=IP)
    res.encoding = 'GB18030'
    page = etree.HTML(res.text)
    bookname = page.xpath('//div[@id="info"]/h1')[0].xpath('string(.)')
    dl = page.xpath('//div[@id="list"]/dl/dd/a')
    splitHTTP = parse.urlsplit(url)
    url = splitHTTP.scheme + '://' + splitHTTP.netloc
    return list(map(lambda x: url + x.get('href'), dl)), bookname


def BuildGevent(baseurl):
    content, bookname = getContentFile(baseurl)  # version2
    steps = 500
    beginIndex, length = steps, len(content)
    count = 0
    name = "%s.txt" % bookname
    while (count - 1) * steps < length:
        data = {}

        WaitigList = [gevent.spawn(getNoval, content[i + count * steps], i + count * steps, data) for i in range(steps) if
                      i + count * steps < length]
        gevent.joinall(WaitigList)

        String = '\n'.join(data.values())
        if count == 0:
            with open('./Noval/' + name, 'w', encoding='gb18030', errors='ignore') as ff:
                ff.write(String)
        else:
            with open('./Noval/' + name, 'a', encoding='gb18030', errors='ignore') as ff:
                ff.write(String)
        count += 1


if __name__ == '__main__':
    starttime = time.time()
    setDir()
    # url = 'http://www.biquge.com.tw/2_2826/'
    url = 'http://www.biquge.com.tw/14_14969/'
    BuildGevent(url)
    endtime = time.time()
    print("Total use time: %.6f" % (endtime - starttime))

猜你喜欢

转载自blog.csdn.net/a19990412/article/details/80149453