1. 程式人生 > >【Python3爬蟲-爬小說】爬取某小說網小說2/2--利用下一頁抓

【Python3爬蟲-爬小說】爬取某小說網小說2/2--利用下一頁抓

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

-

詳細思路參照程式碼註釋:

如下:網址無任何規律,但是頁面有一個下一頁。那是要抓到下一頁的地址就能把小說全部抓取。

-

from bs4 import BeautifulSoup
import urllib.request
import re


def down(url, num):

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

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

    # 獲取小說標題
    try:
        # 匹配抓取區域
        pid1 = str(soup.findAll('h3', {"class": "j_chapterName"})[0])

        # 清除html標籤
        pattern = re.compile(r'<[^>]+>', re.S)
        result1 = pattern.sub('', pid1)

        # 將抓取區域儲存至txt檔案
        fh = open(name + '.txt', 'a', encoding='utf-8')  # 制定txt編碼,避免中文編碼解析報錯。a可以持續寫入檔案,w每次會覆蓋之前的內容
        fh.write("\n" + result1)
        fh.close()

        print("標題頁數=" + str(num) + "標題寫入完成")
        pass
    except:
        print("標題報錯頁數=" + str(num))
        pass

    # 獲取小說內容
    try:
        # 匹配抓取區域
        pid2 = str(soup.findAll('div', {"class": "read-content j_readContent"})[0])

        # 清除html標籤
        pattern2 = re.compile(r'<[^>]+>', re.S)
        result2 = pattern2.sub('', pid2)

        # 將抓取區域儲存至txt檔案
        fh = open(name + '.txt', 'a', encoding='utf-8')  # 制定txt編碼,避免中文編碼解析報錯。a可以持續寫入檔案,w每次會覆蓋之前的內容
        fh.write("\n" + result2)
        fh.close()

        print("頁數=" + str(num) + "內容寫入完成")
    except:
        print("內容報錯頁數=" + str(num))
        pass

    # 獲取下一頁的連結
    try:
        pid = soup.findAll('a', {"id": "j_chapterNext"})[0]
        next_a = "https:" + pid['href']
        num += 1

        # global timer  # 無限setInterval模式
        # timer = threading.Timer(0.5, down(next_a, num))  # 延時0秒
        # timer.start()

        down(next_a, num)  # 下一頁

        # print(next_a)
        print("自動執行下一頁=" + num + str(next_a))
        pass
    except:
        print("無下一頁,抓取完成。")
        pass

    pass


# 小說資訊
name = "鳳策長安-文字版"  # 小說書名
info_class = "連載中,古代言情,古典架空,17.82萬字"  # 小說類別
info_detail = "鳳輕 著。狐狸窩系列之二看血狐女神如何叱吒亂世!別人穿越是宅鬥宮鬥打臉虐渣,迎娶皇子王爺走上人生巔峰。楚凌穿越是逃命、逃命、還是逃命!"  # 小說簡介
info_source = "來源:https://www.readnovel.com/book/11908179003210301#Catalog"  # 小說目錄地址

# 寫入小說資訊
fh = open(name + '.txt', 'a', encoding='utf-8')
fh.write("《" + name + "》" + " || " + info_class + " || " + info_detail + " || " + info_source + "\n\n")
fh.close()

down("https://www.readnovel.com/chapter/11908179003210301/31965775208355765", 1)  # 第一頁

-

-