1、網頁查看
進入到全部小說,這就是我們要爬取的小說,這些夠看很長時間了
2、完整代碼及注釋分析

import requests from bs4 import BeautifulSoup import os import re headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36" } #保存路徑 path = "./小說" #如果路徑不存在就創建 if not os.path.exists(path): os.mkdir(path) #訪問的url url = "http://www.xbiquge.la/xiaoshuodaquan/" #發起get請求 response = requests.get(url=url, headers=headers) #注意設置編碼,不然為亂碼 response.encoding = "utf-8" #解析網頁 data = BeautifulSoup(response.text, "html.parser") #參考圖1,獲取ul下的所有li ul = data.find(class_="novellist").find_all("li") #遍歷 for li in ul: li_data = BeautifulSoup(str(li), "html.parser") #參考圖2 #小說名稱 name = li_data.find("a").text #詳情頁url page_url = li_data.find("a")["href"] #拼接路徑 path = path + "/" + name print("正在爬取:"+name) if not os.path.exists(path): os.mkdir(path) #向詳情頁發起請求 page_response = requests.get(url=page_url, headers=headers) page_response.encoding = "utf-8" page_data = BeautifulSoup(page_response.text, "html.parser") #參考圖3 dl = page_data.find("dl").find_all("dd") #遍歷dl for dd in dl: dd_data = BeautifulSoup(str(dd),"html.parser") #參考圖4 chapter = dd_data.find("a").text chapter_url = "http://www.xbiquge.la" + dd_data.find("a")["href"] #對每一章節url發起請求 res = requests.get(url=chapter_url,headers=headers) res.encoding = "utf-8" try: #參考圖5 #獲取每一章節中的文本內容,使用select選擇器進行定位 text = BeautifulSoup(res.text,"html.parser").select("#content")[0].text except: pass #使用正則進行替換 section_text = re.sub('\s+', '\r\n\t', text).strip('\r\n').replace("親,點擊進去,給個好評唄,分數越高更新越快,據說給新筆趣閣打滿分的最后都找到了漂亮的老婆哦!手機站全新改版升級地址:http://m.xbiquge.la,數據和書簽與電腦站同步,無廣告清新閱讀!","") #保存文件 with open(path +"/"+chapter+".txt",'wb') as f: f.write(section_text.encode("UTF-8"))
3、圖片輔助分析
圖1
圖2
圖3
圖4
圖5