用PYTHON爬蟲簡單爬取網(wǎng)絡小說。
這里是17K小說網(wǎng)上,隨便找了一本小說,名字是《千萬大獎》。
里面主要是三個函數(shù):
1、get_download_url() 用于獲取該小說的所有章節(jié)的URL。
分析了該小說的目錄頁http://www.17k.com/list/2819620.html的HTML源碼,發(fā)現(xiàn)其目錄是包含在Volume里的A標簽合集。所以就提取出了URLS列表。
2、get_contents(target) 用于獲取小說指定章節(jié)的正文內(nèi)容
分析了小說中第一章節(jié)的頁面http://www.17k.com/chapter/2819620/34988369.html,發(fā)現(xiàn)其正文內(nèi)容包含在P標簽中,正文標題包含在H1標簽中,經(jīng)過對換行等處理,得到正文內(nèi)容。傳入?yún)?shù)是上一函數(shù)得到的URL。
3、writer(name, path, text) 用于將得到的正文內(nèi)容和章節(jié)標題寫入到千萬大獎.txt
理論上,該簡單爬蟲可以爬取該網(wǎng)站的任意小說。
from bs4 import BeautifulSoup
import requests, sys
'''
遇到不懂的問題?Python學習交流群:821460695滿足你的需求,資料都已經(jīng)上傳群文件,可以自行下載!
'''
target='http://www.17k.com/list/2819620.html'
server='http://www.17k.com'
urls=[]
def get_download_url():
req = requests.get(url = target)
html = req.text
div_bf = BeautifulSoup(html,'lxml')
div = div_bf.find_all('dl', class_ = 'Volume')
a_bf = BeautifulSoup(str(div[0]),'lxml')
a = a_bf.find_all('a')
for each in a[1:]:
urls.append(server + each.get('href'))
def get_contents(target):
req = requests.get(url = target)
html = req.text
bf = BeautifulSoup(html,'lxml')
title=bf.find_all('div', class_ = 'readAreaBox content')
title_bf = BeautifulSoup(str(title[0]),'lxml')
title = title_bf.find_all('h1')
title=str(title[0]).replace('
','')
title=str(title).replace('
','')
title=str(title).replace(' ','')
title=str(title).replace('\n','')
texts = bf.find_all('div', class_ = 'p')
texts=str(texts).replace('
','\n')
texts=texts[:texts.index('本書首發(fā)來自17K小說網(wǎng),第一時間看正版內(nèi)容!')]
texts=str(texts).replace(' ','')
return title,str(texts[len('[
'):])
def writer(name, path, text):
write_flag = True
with open(path, 'a', encoding='utf-8') as f:
f.write(name + '\n')
f.writelines(text)
f.write('\n')
#title,content=get_contents(target)
#print(title,content)
#writer(title,title+".txt",content)
get_download_url()
#print(urls)
i=1
for url in urls:
title,content=get_contents(url)
writer(title,"千萬大獎.txt",content)
print(str(int(i/len(urls)*100))+"%")
i+=1
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
