python爬蟲爬取小說內容(Python爬蟲自學筆記爬取小說)
2023-06-07 07:37:28 3
1 功能及版本說明功能:爬取小說目錄和章節內容,並將章節內容下載到本地txt文件中。
版本:v1.1
增加代理IP,實現小說完整下載。
2 開發環境開發環境:Python3和PyCharm;
3 網站介紹及分析以免費小說全文閱讀網站(http://www.quanwenyuedu.io/)為例,爬取該網站上面的小說。通過快捷鍵F12,可以調出當前網頁的源碼信息,分析相關源碼。
首先看小說目錄頁面,通過點擊藍色邊框內的箭頭,再點擊左側頁面中要了解的信息,在右側就會出現相關的源碼信息。
小說名稱"遮天"對應的源碼為:遮天;
小說作者"作者:辰東"對應的源碼為:"作者:"辰東;
小說章節信息對應的源碼為:第1章 星空中的青銅巨棺;
下面看章節內容頁面,發現小說具體章節內容在代碼......中。
1) 提供小說目錄頁的url;
2) 爬取目錄頁面信息;
3) 提取目錄頁面中小說的名稱、作者、具體章節的名稱和網址信息;
4) 根據提取到的章節網址(一般為相對路徑網址),結合目錄頁網址進行分析,合成絕對路徑的章節網址;
5) 爬取小說章節網頁內的正文內容,判斷網站是否訪問成功,若訪問不成功則隨機選取代理IP,繼續訪問;若訪問成功,則將正文內容保存到本地txt文件中;
6) 循環小說章節網址,依次爬取下載保存到本地。
5 代碼實現代碼分兩個py文件,crawl_v1.1.py為爬取小說並下載的代碼,proxy_ip.py為爬取代理IP的代碼,具體如下:
完整代碼如下:
crawl_v1.1.py
# 爬取小說 v1.1import requestsfrom bs4 import BeautifulSoupimport timeimport randomimport proxy_ipurl = "http://www.quanwenyuedu.io/n/zhetian/xiaoshuo.html"# 爬取url網址內容def get_url(url,proxies): headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0", "Accept":"text/html,application/xhtml xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding":"gzip, deflate, sdch", "Accept-Language":"zh-CN,zh;q=0.8", "Cache-Control":"max-age=0", "Connection":"keep-alive"} r = requests.get(url,headers = headers,proxies = proxies) while r.status_code != 200: p = proxy_ip.get_random_ip r = requests.get(url, headers=headers, proxies=p) return r# 獲取小說名稱和作者proxies_random = proxy_ip.get_random_ipr = get_url(url,proxies_random)soup = BeautifulSoup(r.text,"html.parser")title = soup.h1.textauthor = soup.find_all("p")[1].text[3:]chapter_list = soup.find_all("li")for i in chapter_list: # 獲取小說章節名稱和網址 i_url = i.a.get("href") chapter_url = url[:-13] i_url chapter_name = i.text # 獲取小說章節內容 r = get_url(chapter_url,proxies_random) chapter_soup = BeautifulSoup(r.text,"html.parser") content = chapter_soup.find_all("p") # 將章節內容寫入txt文件 print(chapter_name " 正在下載......") for c in content: with open(title "_" author ) as f: f.write(c.text "\n") print(chapter_name " 下載完成")
proxy_ip.py
# 爬取代理IPimport requestsfrom bs4 import BeautifulSoupimport randomurl = "https://www.xicidaili.com/nn"headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0", "Accept": "text/html,application/xhtml xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch", "Accept-Language": "zh-CN,zh;q=0.8", "Cache-Control": "max-age=0", "Connection": "keep-alive"}ip_list = []r = requests.get(url,headers = headers)soup = BeautifulSoup(r.text,"html.parser")# 提取ip相關的標籤tr = soup.find_all("tr")tr = tr[1:]for i in tr: td = i.find_all("td") td_2 = td[1].text td_3 = td[2].text td_6 = td[5].text ip = td_6 "://" td_2 ":" td_3 ip_list.append(ip)def get_random_ip: ip_random = random.choice(ip_list) i = ip_random.find(":") # 定位":",便於提取"http"或"https" proxy = {ip_random[:i]:ip_random} return proxy
代碼運行效果如下:
1) 在代碼調試階段,出現如下錯誤:
UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 7: illegal multibyte sequence
經查詢分析,write函數的默認編碼不是utf-8,在write中設置utf-8編碼:write("","a",encoding="utf-8");
2) 下載速度過慢;
3) 代碼運行,小說下載到990章時停住了,運行沒有結束,也沒有給出錯誤代碼,只是不再繼續運行下去了;
原因分析:懷疑是內存不足,或者寫入函數write內存限制。
7 相關學習知識點1) 列表追加元素:list.append[];
2) 隨機選取列表中的元素:需要引入random庫,調用random.choice函數;
3) 其他py文件中函數的調用:在要引入的文件中定義函數def get_random_ip;在本文件中import py文件,並調用get_random_ip函數;
4) While循環語句,判斷網站訪問是否成功;
8 結束語本次代碼解決了反爬蟲訪問限制的問題,但下載速度很慢,且在進行到990章時代碼運行停止了,沒有給出錯誤原因,需要進一步優化。
將此次編碼的過程及源碼分享給大家,供大家參考。對於錯誤的地方,或有更好的建議,希望大家提出來,不勝感激!
,