多进程爬虫(爬取小说)Python实现
生活随笔
收集整理的這篇文章主要介紹了
多进程爬虫(爬取小说)Python实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
區別于之前用多協程寫的爬蟲版本
多協程爬取小說
這個版本,開銷會比較大。效率上也不一定有之前的高
不過,總體上還是很不錯的~
問題分析
這個版本,還有之前的版本都一樣,還存在問題,就是在下載好了文件之后,我們這里是會先打包成每個章節的小說,再通過一個腳本來,將這些章節整合起來,放到了小說文件中。但是,實際上,這樣反反復復地寫文件,刪除文件,是非常耗時間的。
如果信息,都是直接存在內存當中,再通過這個方式再來直接寫入文件,會快很多。
但是這樣就涉及到了進程間的通信了。通過這樣的方式,完全可以維護一個字典。那樣,開啟進程的時候,就直接對所有的章節都開啟一個進程就好了,對于那個被所有的人都在維護的字典,我們就做一個很簡單的 關于index的排序,這樣就可以直接做到了爬取的提速。
上面的這些,其實在之前的協程中就很想用到了,但是,在協程中,最多監聽1200個協程。所以,這個涉及就沒有在之前的協程中體現出來。
但是在申請進程的時候,開銷太大的了(相比于協程),所以導致了,在這里,用的時間,比之前用協程要慢。但是,可以通過這個方式來提高速度。應該說前景更大吧。總之,這是用多進程寫的這個爬蟲的第一個版本。后續還會完善。
import requests import os import multiprocessing import random import re from lxml import etree from urllib import parse import timedef setDir():if 'Noval' not in os.listdir('./'):os.mkdir('./Noval')def getNoval(url, id):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; ctrl_time=1; CNZZDATA1272873873=2070014299-1518497311-https%253A%252F%252Fwww.baidu.com%252F%7C1518507528; yjs_id=69163e1182ffa7d00c30fa85105b2432; jieqiVisitTime=jieqiArticlesearchTime%3D1518509603'}IPs = [{'HTTPS': 'https://115.237.16.200:8118'},{'HTTPS': 'https://42.49.119.10:8118'},{'HTTPS': 'http://60.174.74.40:8118'}]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(.)")with open('./Noval/%d.txt' % id, 'w', encoding='gb18030', errors='ignore') as f:f.write(s)def getContentFile(url):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; ctrl_time=1; CNZZDATA1272873873=2070014299-1518497311-https%253A%252F%252Fwww.baidu.com%252F%7C1518507528; yjs_id=69163e1182ffa7d00c30fa85105b2432; jieqiVisitTime=jieqiArticlesearchTime%3D1518509603'}IPs = [{'HTTPS': 'https://115.237.16.200:8118'},{'HTTPS': 'https://42.49.119.10:8118'},{'HTTPS': 'http://60.174.74.40:8118'}]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.netlocreturn list(map(lambda x: url + x.get('href'), dl)), booknamedef BuildGevent(baseurl):content, bookname = getContentFile(baseurl) # version2steps = 10beginIndex, length = steps, len(content)count = 0name = "%s.txt" % booknamewhile (count - 1) * steps < length:WaitigList = [multiprocessing.Process(target=getNoval, args=(content[i + count * steps], i + count * steps)) for i in range(steps) ifi + count * steps < length]for p in WaitigList:p.start()for p in WaitigList:p.join()NovalFile = list(filter(lambda x: x[:x.index('.')].isdigit(), os.listdir('./Noval')))NovalFile.sort(key=lambda x: int(re.match('\d+', x).group()))String = ''for dirFile in NovalFile:with open('./Noval/' + dirFile, 'r', encoding='gb18030', errors='ignore') as f:String = String + '\n' + f.read()os.remove('./Noval/%s' % dirFile)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/6_6107/'BuildGevent(url)endtime = time.time()print("Total use time: %.6f" % (endtime - starttime))總結
以上是生活随笔為你收集整理的多进程爬虫(爬取小说)Python实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【2018年更新】Sublime tex
- 下一篇: %r或者{!r}在python中的意思