欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

python按章节分割txt_python爬虫,爬取小说

发布时间:2025/3/15 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python按章节分割txt_python爬虫,爬取小说 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

功能:爬取并下载小说中非vip部分的内容。

对于一个有八九年书龄的老书虫而言,遇到想看的小说,却没有找到下载的窗口,每次阅读都需要网上搜索,特别是网不好的地方,是十分不方便的。因此利用python写了爬取小说的代码。

以爬取笔趣阁中的求魔小说为例。

  • 首先,打开笔趣阁网站,找到求魔这本小说,网址为:https://www.biquge.info/10_10142/。

  • 打开vs code软件(本人采用vs coede写python),导入数据包。
import requests import parsel from lxml import etree import os
  • 获得所有章节的网址。

利用request获得网页内容。

response = requests.get('https://www.biquge.info/10_10142/') response.encoding = response.apparent_encoding #对网页进行解析,防止网页乱码

利用xpath获得每一个章节的地址。

html = etree.HTML(response.text) url_s = html.xpath('//*[@id="list"]/dl/dd') #url_s里存放所有章节地址
  • 爬取每一个章节内容。

获得要爬取章节的地址。

for url in url_s:url_one = url.xpath('./a/@href')print('https://www.booktxt.net/5_5871/' +url_one[0])download_one_chapter('https://www.booktxt.net/5_5871/' +url_one[0])

对单个章节内容进行爬取。

def download_one_chapter(url):#爬取一章response = requests.get(url) #请求网页,获取网页数据response.encoding = response.apparent_encoding #解决乱码问题 万能解码sel = parsel.Selector(response.text) #将字符串变成网页#########爬取文章标题###############h1 = sel.css('h1::text') #css选择器 'h1::text'将对象变为字符串title = h1.get()if os.path.exists('txt/' +title +'.txt'):return print(title)#########爬取文章内容content = sel.css('#content::text')title = h1.get()lines = content.getall()text = ''for line in lines:text += line.strip() + 'n'
  • 对每一章的内容进行保存。

建立txt文件夹,每一章内容保存在该文件夹中。

with open('txt/' +title +'.txt','w',encoding = 'utf-8') as f:f.write(title)f.write(text)

代码:https://github.com/kj267123-wu/python-

总结

以上是生活随笔为你收集整理的python按章节分割txt_python爬虫,爬取小说的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。