生活随笔
收集整理的這篇文章主要介紹了
爬取小说2--协程间通信Python
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
通過Python進(jìn)行協(xié)程間通信,大大加速爬取效率。
前言
是這樣的,在之前的爬蟲版本中,我們通過并發(fā)技術(shù)(python協(xié)程只是并發(fā))。實(shí)現(xiàn)快速爬取小說的效果。
將速度提高為原來的幾百倍了。但是卻由于之前的多協(xié)程之間的通信,都是采用寫入硬盤之后,再相互通信來實(shí)現(xiàn)的,所以,速度上還是存在一定的缺陷。
最新
在最新的版本中,我們采用多協(xié)程技術(shù),采用在內(nèi)存通信,這樣來傳遞爬取的數(shù)據(jù),之后,再來組合成為新的章節(jié),這樣就可以做到了對于之前版本的提速效果。而且需要代碼量也下降了10行左右。
還是跟之前的版本一樣目標(biāo)小說網(wǎng)站只能是http://www.biquge.com.tw/這個(gè)網(wǎng)站下的小說的目錄頁
只要把目錄頁對應(yīng)的小說的網(wǎng)址丟到main函數(shù)中的url里面,就可以實(shí)現(xiàn)了小說爬取。
小調(diào)整tips:
當(dāng)然啦,根據(jù)自己的需求,可以試試看改改BuildGevent函數(shù)的step變量。這個(gè)表示每次發(fā)多少個(gè)協(xié)程。注意,最多是1200個(gè)。
這個(gè)設(shè)置,可以自己考慮,根據(jù)不同的設(shè)備情況,網(wǎng)絡(luò)效果,對方服務(wù)器的穩(wěn)定程度來進(jìn)行判斷。
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 timeIPs = [{
'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 = HEADERSIP = 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:
continueelse:
breakdef getContentFile(url):headers = HEADERSIP = 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) steps =
500beginIndex, length = steps, len(content)count =
0name =
"%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)
ifi + 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 +=
1if __name__ ==
'__main__':starttime = time.time()setDir()url =
'http://www.biquge.com.tw/14_14969/'BuildGevent(url)endtime = time.time()print(
"Total use time: %.6f" % (endtime - starttime))
總結(jié)
以上是生活随笔為你收集整理的爬取小说2--协程间通信Python的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。