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

 

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