1. 程式人生 > >【Python3爬蟲-爬小說】爬取某小說網小說1/2--利用網址順序抓

【Python3爬蟲-爬小說】爬取某小說網小說1/2--利用網址順序抓

宣告:爬蟲為學習使用,請各位同學務必不要對當放網站或i伺服器造成傷害。務必不要寫死迴圈。

-

練習目標:爬取https://b.faloo.com/BuyBook.aspx?id=526024 《我的高中女友門》

-

解釋請看程式碼註釋:

主要是網頁是xxx/1.html,xxx/2.html這種數字遞增的網頁;小說內容在id=content這個地方。

from bs4 import BeautifulSoup
import urllib.request


def down(url, num):

    # 獲取網頁
    response = urllib.request.urlopen(url)
    html = response.read().decode('gbk')  # 編碼格式gb2312,utf-8,GBK
    html_string = str(html)  # 轉換成string,可以直接向資料庫新增

    soup = BeautifulSoup(html_string, "html.parser")  # 解析網頁標籤

    try:
        # 匹配抓取區域
        # pid = soup.find(attrs={"id": "content"})
        pid = str(soup.findAll('div', {"id": "content"})[0])
        print("當前頁數=" + str(num))
        print(type(pid))

        # 將抓取區域儲存至txt檔案
        fh = open('我的高中女友們.txt', 'a', encoding='utf-8')  # 制定txt編碼,避免中文編碼解析報錯。a可以持續寫入檔案,w每次會覆蓋之前的內容
        fh.write(pid)
        fh.close()
        print("頁數=" + str(num) + "寫入完成")
    except:
        print("報錯頁數=" + str(num))

    pass


# 有多少個該小說網頁
num = 1  # 開始頁
while num <= 50:  # 結束頁
    down("https://b.faloo.com/p/526024/" + str(num) + ".html", num)
    num += 1
    pass
else:
    print("完成")
    pass

-

-