python按章节分割txt_python爬虫,爬取小说
生活随笔
收集整理的這篇文章主要介紹了
python按章节分割txt_python爬虫,爬取小说
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
功能:爬取并下載小說中非vip部分的內容。
對于一個有八九年書齡的老書蟲而言,遇到想看的小說,卻沒有找到下載的窗口,每次閱讀都需要網上搜索,特別是網不好的地方,是十分不方便的。因此利用python寫了爬取小說的代碼。
以爬取筆趣閣中的求魔小說為例。
- 首先,打開筆趣閣網站,找到求魔這本小說,網址為:https://www.biquge.info/10_10142/。
- 打開vs code軟件(本人采用vs coede寫python),導入數據包。
- 獲得所有章節的網址。
利用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爬虫,爬取小说的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中函数的使用_python中
- 下一篇: python爬火车票_python爬取1