python爬蟲,爬取筆趣閣小說內容,最後n章內容,並保存到txt文件中,以《劍來》爲例

之前我有寫一個小說的爬蟲,後來那個網站可能不行了,我看哪個《筆趣閣》挺穩定的,所以拿來爬點數據。

原來爬蟲博客:https://blog.csdn.net/qq_38190111/article/details/84668878

原來自動發送郵件博客:https://blog.csdn.net/qq_38190111/article/details/100160697

其實最大的難點之前這兩個博客已經解決了,所以,我只不過是換個網址,換了html標籤的選擇而已。

這個shell 工具在我調試的時候每次都很艱難的炸掉。 

代碼每行什麼意思我不想過多贅述、自己試一次就知道了,懂html標籤的都能明白python爬蟲的其實! 

import os
import requests
from bs4 import BeautifulSoup

dest = "d://劍來.txt"
if os.path.exists(dest) is None:
    os.mkdir(dest)
f = open(dest,'w')
f.close()


url=input("輸入筆趣閣網址:")
res=requests.get(url)
res.encoding = res.apparent_encoding
data = res.text
html = BeautifulSoup(data,'lxml')
dds = html.find_all('dd')
count = input("需要最後幾章小說(填入數字):")
for dd in dds[-int(count):]:
    href = dd.find('a').get('href');
    #print("章節html爲:"+href)
    href = url+href
    res = requests.get(href)
    data = res.text.encode('iso-8859-1',"ignore").decode('utf-8')
    html = BeautifulSoup(data,'lxml')
    title = html.find('h1').text
    print(title+" 下載成功")
    content = html.find('div',attrs={"id":"content"})
    content = content.text.replace('<br/>','\n')
    with open(dest,'a',encoding='utf-8') as f:
        f.write("***************"+title+"***************\n")
        f.write(content)
        f.write("\n\n\n\n")
        print(title+"保存成功")
    f.close()
print("筆趣閣小說最後"+ count +"章下載完畢")

最後的運行結果:

 文件:

好久沒看總管的劍來了,誰讓他擠牙膏,直接過一段時間去爬幾十篇一起看了好了,天天等他跟新還不等個要死。。。

怎麼樣,自己動手,下載下來的小說,是不是非常的滿意呢?哈哈哈

通過email發送文件到我的kindle地址,就可以在kindle上享用了,這個週末又有找落了,

上述代碼,適合所有筆趣閣小說的爬取喲~~~

over

 

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