系列文章目錄
python爬蟲實戰——爬取淘寶商品資訊并匯入EXCEL表格(超詳細)
python多執行緒爬取壁紙 媽媽再也不擔心我沒壁紙了!.
python爬蟲爬取虎牙資料(簡單利用requests庫以及Beautifulsoup).
python爬蟲之爬取壁紙(新手入門級).
python爬蟲實戰——爬取貓眼電影TOP100并匯入excel表
文章目錄
- 系列文章目錄
- 前言
- 一、網頁決議
- 二、代碼填寫
- 1.獲取Html及寫入方法
- 2.其余代碼
- 總結
前言
利用python寫一個簡單的筆趣閣爬蟲,根據輸入的小說網址爬取整個小說并保存到txt檔案,爬蟲用到了BeautifulSoup庫的select方法
結果如圖所示:

本文只用于學習爬蟲
一、網頁決議
這里以斗羅大陸小說為例 網址:
http://www.biquge001.com/Book/2/2486/

可以發現每章的網頁地址和章節名都放在了 <"div id=list dl dd a>中的a標簽中,所以利用BeautfulSoup中的select方法可以得到網址和章節名
Tag = BeautifulSoup(getHtmlText(url), "html.parser") #這里的getHtmlText是自己寫的獲取html的方法
urls = Tag.select("div #list dl dd a")
然后遍歷串列
for url in urls:
href = "http://www.biquge001.com/" + url['href'] # 字串的拼接 拼接成正確的網址
pageName = url.text # 每章的章名
然后每章小說的內容都存放在<div id=“content” 里 同理得

substance = Tag.select("div #content") # 文章的內容
最后同理在首頁獲取小說的名稱
<"div id = info h1>

bookName = Tag.select("div #info h1")
二、代碼填寫
1.獲取Html及寫入方法
def getHtmlText(url):
r = requests.get(url, headers=headers)
r.encoding = r.apparent_encoding # 編碼轉換
r.raise_for_status()
return r.text
def writeIntoTxt(filename, content):
with open(filename, "w", encoding="utf-8") as f:
f.write(content)
f.close()
print(filename + "已完成")
2.其余代碼
代碼如下(示例):
url = "http://www.biquge001.com/Book/2/2486/"
substanceStr = ""
bookName1 = ""
html = getHtmlText(url)
# 判斷是否存在這個檔案
Tag = BeautifulSoup(getHtmlText(url), "html.parser")
urls = Tag.select("div #list dl dd a")
bookName = Tag.select("div #info h1")
for i in bookName:
bookName1 = i.text
if not os.path.exists(bookName1):
os.mkdir(bookName1)
print(bookName1 + "創建完成")
else:
print("檔案已創建")
for url in urls:
href = "http://www.biquge001.com/" + url['href'] # 字串的拼接 拼接成正確的網址
pageName = url.text # 每章的章名
path = bookName1 + "\\" # 路徑
fileName = path + url.text + ".txt" # 檔案名 = 路徑 + 章節名 + ".txt"
Tag = BeautifulSoup(getHtmlText(href), "html.parser") # 決議每張的網頁
substance = Tag.select("div #content") # 文章的內容
for i in substance:
substanceStr = i.text
writeIntoTxt(fileName, substanceStr)
time.sleep(1)
總結
簡單利用了BeautfulSoup的select方法對筆趣閣的網頁進行了爬取轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/247663.html
標籤:python
上一篇:task01,lc:2,4,5
