Python爬取小說全書網

給大家分享一個爬取小說的代碼,這次的代碼很簡單,而且只需要修改一下地方就可以爬取全書網的任意小說。對於爬取小說我們都知道需要爬取章節名稱,小說內容。所以接下來我就講解部分主要代碼,後面附上完整代碼。

第一步,獲取網頁源代碼,正則表達式匹配鏈接和標題。處理字符

#獲取網頁源代碼
    html=urllib.request.urlopen("http://www.quanshuwang.com/book/2/2131").read()
    #處理字符
    html=html.decode("gbk")
    #print(html)
    #正則匹配,分組匹配
    reg=r'<a href="(.*?)" title=".*?">(.*?)</a></li>'
    #增加效率
    reg=re.compile(reg)

第二步,獲取每個章節的題目和鏈接,並打開,採用正則表達式匹配小說內容。

#獲取章節鏈接並打開
        novel_url=url[0]
        novel_title=url[1]
        chapt=urllib.request.urlopen(novel_url).read()
        chapt_html=chapt.decode("gbk")
        #print(chapt_html)
        #正則表達式獲取文章內容
        reg=r'</script>&nbsp;&nbsp;&nbsp;&nbsp;(.*?)<script type="text/javascript">'
        #匹配換行,S多行匹配
        reg=re.compile(reg,re.S)
        chapt_content=re.findall(reg,chapt_html)

之後我們爬取的內容如下;

對爬取的內容進行預處理。替換空格和<br />


        chapt_content=chapt_content[0].replace("&nbsp;&nbsp;&nbsp;&nbsp;","")
        chapt_content=chapt_content.replace("<br />","")

結果如下:

接下來就是保存到本地,這裏我給大家分享兩種方法,一種是每一章節保存一個TXT文件,另外一中就是全部保存到一個TXT文件中,代碼如下:

f=open('{}.txt'.format(novel_title),'w')
        f.write(chapt_content)
        #with open('C:/Users/ASUS/Desktop/12.txt','a',encoding='utf-8') as f:
            #f.write(chapt_content)
            #f.close()

效果如下:

後面一個是全部保存到一個TXT文件中的,接下來就是完整的代碼;

# coding=utf-8

import urllib.request
import re
#駝峯命名、獲取小說內容
def getNoverContent():
    #獲取網頁源代碼
    html=urllib.request.urlopen("http://www.quanshuwang.com/book/2/2131").read()
    #處理字符
    html=html.decode("gbk")
    #正則匹配,分組匹配
    reg=r'<a href="(.*?)" title=".*?">(.*?)</a></li>'
    #增加效率
    reg=re.compile(reg)
    #查找所有
    urls=re.findall(reg,html)
    #元組
    for url in urls:
        #獲取章節鏈接並打開
        novel_url=url[0]
        novel_title=url[1]
        chapt=urllib.request.urlopen(novel_url).read()
        chapt_html=chapt.decode("gbk")
        #print(chapt_html)
        #正則表達式獲取文章內容
        reg=r'</script>&nbsp;&nbsp;&nbsp;&nbsp;(.*?)<script type="text/javascript">'
        #匹配換行,S多行匹配
        reg=re.compile(reg,re.S)
        chapt_content=re.findall(reg,chapt_html)
        #替換空格
        chapt_content=chapt_content[0].replace("&nbsp;&nbsp;&nbsp;&nbsp;","")
        chapt_content=chapt_content.replace("<br />","")
    
        print("正在爬取%s"%novel_title)
        #保存爲txt文件
        f=open('{}.txt'.format(novel_title),'w')
        f.write(chapt_content)
        #with open('C:/Users/ASUS/Desktop/12.txt','a',encoding='utf-8') as f:
            #f.write(chapt_content)
            #f.close()
print("爬取完成")
getNoverContent()    


好了,今天就分享到這裏,有什麼不對的地方還望各位大佬指正修改。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章