python 爬蟲入門--抓取紅樓夢小說

爬蟲抓取網頁的三個基本步驟:

  • 獲取網頁 html (用 request 包)
  • 解析網頁,找到我們想要的內容(用 beautifulsoup 包等)
  • 輸出內容

找到一個在線紅樓夢網址:http://www.shicimingju.com/book/hongloumeng.html

從這個網站抓取紅樓夢,不過這個網站缺少 28 回,代碼如下:

# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 20:59:20 2020

@author: zhen chen

MIT Licence.

Python version: 3.7


Description: crawling the online novle "hong lou meng"
    
"""

import requests  # 聯繫網絡的包,a package for requesting from websites
import re  # 正則表達式包,for cutting the punctuations
from bs4 import BeautifulSoup # 分析網頁數據的包,a package for webstie data analysis
import time 
import random

# 獲取網頁信息
def get_url_content(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36'
    }  # 主要是模擬瀏覽器登錄,防止反爬
    r = requests.get(url, headers=headers, timeout=30)  # 獲取網頁的內容,並返回給r變量,timeout 爲超時時間
    r.raise_for_status() # 檢查返回網頁的內容的狀態碼,200表示成功
    r.encoding = r.apparent_encoding # 統一編碼方式
    return r.text # 返回網頁中的文本內容,數據內容爲 r.content


# 解析出網頁中想要的信息,爬蟲的關鍵步驟
def filter_info(url_text):
    soup = BeautifulSoup(url_text, "lxml")  # 解析網頁返回內容,lxml 是一個解碼方式,效率比較快,被推薦使用
    #title = soup.find('h1').get_text() # 尋找便籤 h1 中的內容,作爲標題
    title = soup.title.text # 也可以這樣獲取 title
    # title = re.sub(r'\s', '', title, count=2)  # 將前兩個空格替換
    # 使用 get_text 可以讀取網頁裏面的換行,而 text 不能
    chapter_content = soup.select('.chapter_content')[0].get_text(separator="\n")  # select(.類名) 查找網頁中的類,因爲返回的是列表,所以跟 [0]
    # chapter_content2 = soup.find_all('div', class_ = 'chapter_content')[0].text
    chapter_content = chapter_content.lstrip()  # 去除左邊的空格
    chapter_content = chapter_content.rstrip()  # 去除右邊的空格
    this_chapter = [title, chapter_content]
    return this_chapter


# 將每章內容輸出到 txt 文檔裏
def write_txt(string_array):
    file_address = 'E:/爬蟲練習/紅樓夢/'  # txt 存放地址
    file_name = string_array[0]
    f = open(file_address+file_name+'.txt', 'w', encoding='utf-8') # 必須跟解碼形式,不然有的網頁中文內容寫不到txt裏
    f.write(string_array[1])
    f.close()
    

# 主函數
def main():
    # 一共 120 回,每一回一個網頁
    for i in range(120):
        try:
            chapter_num = str(i + 1)
            url = 'http://www.shicimingju.com/book/hongloumeng/' + chapter_num + '.html' # 各回的網頁網址
            url_content = get_url_content(url)  # 獲取網頁
            chapter_content = filter_info(url_content)  # 解析網頁內容,提取小說
            write_txt(chapter_content)  # 輸出小說內容到 txt
            time.sleep(random.random()*2) # 每抓一個網頁休息0~2秒,防止被反爬措施封鎖 IP
        except: # 第 28 回缺失,跳過錯誤,繼續抓
            continue
        
main() # 執行函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章