python多線程爬蟲爬取頂點小說內(nèi)容(BeautifulSoup+urllib)

思路

之前寫過python爬取起點中文網(wǎng)小說,多線程則是先把爬取的章節(jié)鏈接存到一個列表里,然后寫一個函數(shù)get_text每次調用這個函數(shù)就傳一個章節(jié)鏈接,那么就需要調用n次該函數(shù)來獲取n章的內(nèi)容,所以可以用for循環(huán)創(chuàng)建n個線程,線程的target就是get_text,參數(shù)就是章節(jié)的url。

被爬取頁面

隨便點開的,辣眼睛哈哈哈


全部章節(jié)頁
from bs4 import *
import socket
import time


#在小說章節(jié)頁爬取所有章節(jié)鏈接
def get_html():
    
    #從你的瀏覽器控制臺復制出http報文的header信息
    header = {'User-Agent':'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0'}
    url = 'https://www.dingdiann.com/ddk81000/'
    
    #發(fā)送一個http請求,讀出網(wǎng)頁內(nèi)容存到html
    req = urllib.request.Request(url,headers=header)
    html = urllib.request.urlopen(req).read()

    #網(wǎng)頁里有中文,需要decode
    html.decode('utf-8','ignore')
    
    #用BeautifulSoup處理html 不加‘lxml’參數(shù)會警告
    soup = BeautifulSoup(html,'lxml')
    
    #chapters用來存放所有章節(jié)的鏈接
    chapters = []
    
    dds = soup.find_all('dd')
    for dd in dds:
        chapters.append('https://www.dingdiann.com'+dd.a.get('href'))
        #print(dd.a.get('href'))
    return chapters

#獲取章節(jié)文本信息
def get_text(url):
    header = {'User-Agent':'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0'}
    req = urllib.request.Request(url,headers=header)
    
    response = urllib.request.urlopen(req)
    html = response.read().decode('utf-8','igore')
    
    #關閉請求 防止服務器拒絕服務
    response.close()
    
    soup = BeautifulSoup(html,'lxml')
    
    
    #title = soup.find(class_='bookname').h1.text
    try:
        #找到章節(jié)名
        title = soup.find(class_='bookname').h1.text
        
        #為中文字符串構造正則表達式,識別出“第X章”
        str = title.encode('utf-8')
        filename = re.search(u'.*章'.encode('utf-8'),str).group().decode('utf-8')
        #用追加方式打開文件,文件名是“第X章”
        f = open('C:/Users/liuxu/Desktop/book/'+filename+ '.txt','w+')
        #寫入標題
        f.write(title+'\n\n')
        #逐行寫入小說段落
        text = soup.find(id='content').text
        lines = re.findall(r'\s{2}\S*',text)
        for line in lines:
            f.write(line+'\n')
        #關閉文件
        f.close()
    except:
        #異常處理 防止因為出錯而中斷爬取程序
        print('error in writing')
        
          
#socket.setdefaulttimeout(20) 
threads = [] 
for chapter in get_html():
    th = threading.Thread(target=get_text,args=(chapter,))
    threads.append(th)

for t in threads:
    t.start()
    #每兩個進程之間間隔3秒 防止報出錯誤“[WinError 10054] 遠程主機強迫關閉了一個現(xiàn)有的連接”
    time.sleep(3)
爬取結果
想和大家討論的部分

個人感覺用了多線程之后速度并沒有很大的提升,速度大致是20個txt文件/分鐘,是否有單個機器上繼續(xù)提升爬取速度的方法?

下一步打算搞點能被封ip的爬取行為,然后學學分布式爬蟲。加油~

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容