python初級實戰案例, 爬取某小說網站並下載到本地txt裏,分別使用bs4 xpath re 3種數據清洗方式爬數據

學python半個月 ,肝完了初級教程和簡單的爬蟲技術

聽說爬蟲初學者畢業的條件就是爬取小說並完整下載下來,於是我開始嘗試用所學完成它

------------------------------------------------------------------------------------------------------------------------------------

想把數據從網頁爬下來,基本步驟就是: 挖掘數據  --- 清洗數據 。

這裏暫時忽略了 模擬瀏覽器、seeion登陸、代理IP等一些應對反爬的措施, 因爲找了個毫無防備的網站

首先我所知道的數據挖掘方式有兩種: urllib庫和resquest庫  ,resquest是對urllib的封裝,用法簡單些,一般不需要用urllib了。

而數據清洗的方式有三種:BeautifulSoup、xpath、re(正則表達式),下面源碼以這三種方式分別爬取同一個小說

 

測試的小說地址:http://www.biquw.com/book/50043/   

沒有用多線程, 3個爬取方式只會一個個分別運行,建議分別註釋後測試效果

# 數據挖掘
import requests
# 數據清洗
from bs4 import BeautifulSoup
from lxml import etree
import re
# 其他
import time

url=r"http://www.biquw.com/book/50043/"    #某篇小說主頁面
html=requests.get(url).content.decode('utf-8') #某篇小說主頁面html源代碼

# **********bs4清洗**********
soup=BeautifulSoup(html,"lxml")
data_list=soup.find('ul')
shuname=soup.img.attrs['alt'] #獲取書名
txt=open(shuname+"_bs4清洗.txt","w")
for book in data_list.find_all('a'):
	data_book=requests.get(url+book['href']).content.decode('utf-8')
	soup=BeautifulSoup(data_book,'lxml')  #章節內容頁的xml對象
	time.sleep(0.5)  # 此處必須延遲  否則會報錯 'NoneType' object has no attribute 'text'  ,可能是xml對象沒出來就.text了
	name=soup.find('div',{'class':'h1title'}).text.replace('正文 ','').replace('章節目錄 ','')  #清洗出章節名稱
	data=soup.find('div',{'id':'htmlContent'}).text.replace('\xa0','')    #清洗出章節內容
	# print(data)
	print("bs4清洗方式 正在下載:"+name)
	txt.write(data+"\n")
	time.sleep(0.1)
txt.close()


# **********xpath清洗**********
html=etree.HTML(html)
shuname=html.xpath('//div[@class="pic"]/img/@alt')[0] #獲取書名
data=html.xpath('//div[@class="book_list"]/ul/li/a') #獲取章節鏈接
txt=open(shuname+"_xpath清洗.txt","w",encoding='utf-8')
for x in data:
	link=url+x.get("href")
	text=requests.get(link).content.decode('utf-8') #章節內容頁的HTML源碼
	html=etree.HTML(text)
	chapterContent=html.xpath('//div[@class="contentbox clear"]/text()') #清洗出章節內容 列表形式
	for dd in chapterContent:  
		txt.write(dd+"\n")
	print("xpath清洗方式 正在下載章節:"+x.text)
	time.sleep(0.1)
txt.close()



# **********正則清洗**********
pat='<h1>(.*?)</h1>'
bookName=re.compile(pat,re.I).findall(html)[0] # 獲取書名

txt=open(bookName+"_正則清洗.txt","w")    #創建txt 以書名取名

pat='<li><a href="(.*?)">(.*?)</a></li>'
data=re.compile(pat,re.I).findall(html) # 獲取 章節鏈接 + 章節名稱 的列表
for i in data:
	link=url+i[0]
	text=requests.get(link).content.decode('utf-8')  #章節內容頁的HTML源碼
	time.sleep(0.3) # 延遲下 防止沒取到值就拿去用了
	pat=r'<div id="htmlContent" class="contentbox clear">(.*?)</div>'
	txt_content=re.compile(pat,re.S).findall(text)
	txt_content=txt_content[0].replace('&nbsp;','').replace('<br />','') #清洗出章節內容
	txt.write(txt_content+"\n") #寫入到txt文件
	print("正則清洗方式 正在下載章節:"+i[1])
	time.sleep(0.1)
txt.close()


全部運行完成的效果

 

學會你可以白嫖小說了,至於白嫖VIP電影 嘿嘿, 我也想學

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章