古詩文網中的名著古籍比較多,選取從這個網站上抓。
https://so.gushiwen.cn/guwen/
可以在上面選取任一個古籍,點擊打開復制鏈接,然後在下面代碼中替換相應古籍的鏈接。
下面代碼中,抓取的是《西遊記》:
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 20:14:04 2020
@author: zhen chen
MIT Licence.
Python version: 3.7
Description: crawing chinese classical literature from gushiwen.cn
"""
import requests # 聯繫網絡的包,a package for requesting from websites
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 get_url_links(url_head_content):
soup = BeautifulSoup(url_head_content, "lxml") # 解析網頁返回內容,lxml 是一個解碼方式,效率比較快,被推薦使用
links = soup.find('div', class_ = 'bookcont') # 每一回的鏈接都在類 span 裏面
links= links.findAll('span')
link_list = []
for each in links:
link_list.append('https://so.gushiwen.cn' + each.a.get('href')) # 獲取每一回的鏈接,存儲到列表裏
return link_list
# 解析出網頁中想要的信息,爬蟲的關鍵步驟
def filter_info(chapter_num, url_text):
soup = BeautifulSoup(url_text, "lxml") # 解析網頁返回內容,lxml 是一個解碼方式,效率比較快,被推薦使用
contents = soup.find('div', class_ = 'contson')
# 使用 get_text 可以讀取網頁裏面的換行,而 text 不能
chapter_title = contents.find('p').get_text() # 第一句話是本回的標題
chapter_titel = '第' + str(chapter_num) + '回 ' + chapter_title.lstrip()
chapter_content = contents.get_text(separator="\n") # find 返回的不是列表,不用跟 [0]
chapter_content = chapter_content.lstrip()
this_chapter = [chapter_titel, 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():
url = 'https://so.gushiwen.cn/guwen/book_46653FD803893E4FBF8761BEF60CD7D9.aspx' # 古詩文網西遊記網址
url_head_content = get_url_content(url) # 獲取網頁
links = get_url_links(url_head_content) # 獲取每一回的鏈接地址
for index, each in enumerate(links):
url_link_content = get_url_content(each) # 獲取每一回的網頁內容
chapter_content = filter_info(index+1, url_link_content) # 解析每一回的網頁內容,獲取小說文本
write_txt(chapter_content) # 輸出小說內容到 txt
time.sleep(random.random()*2) # 每抓一個網頁休息0~2秒,防止被反爬措施封鎖 IP
main()