python爬虫爬取《斗破苍穹》小说全文
生活随笔
收集整理的這篇文章主要介紹了
python爬虫爬取《斗破苍穹》小说全文
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
網(wǎng)絡(luò)爬蟲的入門學(xué)習(xí):python爬蟲爬取小說(shuō)全文
import os
觀察HTML標(biāo)簽可以看出小說(shuō)目錄名都在 <div class=novel_list id=novel10121>的標(biāo)簽內(nèi)的<a href="網(wǎng)址">章節(jié)標(biāo)題</a>中,我們需要從HTML代碼中提取出每一章的標(biāo)題并且通過(guò)a標(biāo)簽中的網(wǎng)址進(jìn)入詳情頁(yè)提取出章節(jié)內(nèi)容,這時(shí)就需要用到bs4庫(kù)中的BeautifulSoup類
總結(jié):以上是所有的步驟,下面是完整的代碼,有興趣的小伙伴可以直接復(fù)制粘貼運(yùn)行(但是要確保所有有需要的庫(kù)的下載完畢,否則會(huì)報(bào)一堆錯(cuò)<#-#>)
import requests import os from bs4 import BeautifulSoup if not os.path.exists('D:/斗破蒼穹'):os.mkdir('D:/斗破蒼穹') url='https://www.rmxs8.com/10121/' headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' } response1=requests.get(url=url,headers=headers) response2=requests.get(url='https://www.rmxs8.com/10121_2/') page_text1=response1.text page_text2=response2.text soup1=BeautifulSoup(page_text1,'lxml') soup2=BeautifulSoup(page_text2,'lxml') a_list1=soup1.select('#novel10121.novel_list a') a_list2=soup2.select('#novel10121.novel_list a') a_list=a_list1+a_list2 for a in a_list:chapter_title=a.stringif chapter_title[0:4]=='斗破蒼穹':title_list=list(chapter_title)for i in range(4):title_list.pop(0)title_str=''for i in range(len(title_list)):title_str+=title_list[i]chapter_title=title_strchapter_url='https://www.rmxs8.com'+a['href']chapter_response=requests.get(url=chapter_url,headers=headers)chapter_text=chapter_response.textchapter_soup=BeautifulSoup(chapter_text,'lxml')chapter_content=chapter_soup.find('div',class_='content').textwith open('D:/斗破蒼穹/'+chapter_title+'.txt','w',encoding='utf-8') as fp:fp.write(chapter_content)fp.close()chapter_response.close()print(chapter_title,'下載完成!!!')以下是運(yùn)行結(jié)果
總結(jié)
以上是生活随笔為你收集整理的python爬虫爬取《斗破苍穹》小说全文的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: android获取悬浮窗权限,Andro
- 下一篇: 用Python爬取猫眼数据分析《无名之辈