下載小說並保存在本地
import bs4,os,requests
i = 0
xiaoShuo_NeiRong = []#定義存儲小說章節內容對象的列表
xiaoShuo_biaoTi = []##定義存儲小說章節標題對象的列表
#從小說網站上下載小說,並保存在txt文檔中
while True:
if i < 20:
resOne = requests.get('http://book.zongheng.com/chapter/457720'+'/'+str(7629918+i)+'.html')#下載小說網頁
i = i+1
#根據是否下載成功,將解析後的對象分別存儲在標題和內容的列表中
if resOne.raise_for_status():
bs4One = bs4.BeautifulSoup(resOne.text)
xiaoShuo_NeiRong.append(bs4One.select('div#chapterContent'))#BeautifulSoup對象調用select()查找內容,返回Tag對象的列表,並放在內容列表中
xiaoShuo_biaoTi.append(bs4One.select('h5'))#BeautifulSoup對象調用select()查找標題,返回Tag對象的列表,並放在內容列表中
else:
break
#將相關內容寫入文件中
for j in range(0,len(xiaoShuo_NeiRong)):
xiaZai_two = open('C:\\Users\\Nick\\Desktop\\python\\drawing\\2\\spam002.txt','a')
xiaZai_two.write(xiaoShuo_biaoTi[j][0].getText())
xiaZai_two.write(xiaoShuo_NeiRong[j][0].getText())
xiaZai_two.close()