日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/15 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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爬虫,爬取小说的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。