本文將從多個方面詳細闡述如何使用Python爬取晉江文學城中的VIP文。
一、環境準備
在開始爬取之前,我們需要準備好Python以及相關依賴庫。以下是主要的依賴庫:
import requests
from bs4 import BeautifulSoup
import re
import time
import random
其中,requests庫用於向網站發起請求,BeautifulSoup庫用於解析網頁的HTML代碼,re庫用於正則表達式匹配,time庫和random庫用於控制程序運行的間隔和隨機數生成。
二、爬取VIP文列表
在晉江文學城中,我們可以通過以下鏈接來獲取VIP文列表:http://vipreader.qidian.com/chapter/1004608738/434555247
為了模擬用戶訪問,我們需要在請求中添加User-Agent頭部,並且設置一個間隔時間以及隨機數,用於防止被網站屏蔽。
url = 'http://vipreader.qidian.com/chapter/1004608738/434555247'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
}
response = requests.get(url, headers=headers)
html = response.content.decode('utf-8')
time.sleep(random.uniform(0.5, 2.0))
接下來,我們可以使用BeautifulSoup庫解析html代碼,找到VIP文列表所在的元素,並且將其信息保存下來。
soup = BeautifulSoup(html, 'html.parser')
novel_list = []
for item in soup.find_all('div', {'class': 'groupWrap'}):
novel = {
'name': item.find('div', {'class': 'groupTitle'}).text,
'url': item.find('a').get('href'),
'author': item.find('a', {'class': 'writer-name'}).text,
'category': item.find('div', {'class': 'groupType'}).text,
'introduction': item.find('div', {'class': 'groupContent'}).text.strip(),
}
novel_list.append(novel)
這樣,我們就成功地獲取了VIP文列表的信息,並且保存在novel_list中。
三、爬取VIP章節內容
對於每一個VIP文,我們可以通過其url獲取其章節信息。以下是獲取章節信息的代碼:
def get_chapter_content(url):
response = requests.get(url, headers=headers)
html = response.content.decode('utf-8')
time.sleep(random.uniform(0.5, 2.0))
soup = BeautifulSoup(html, 'html.parser')
content = soup.find('div', {'class': 'read-content j_readContent'}).text.strip()
title = soup.find('h3', {'class': 'j_chapterName'}).text.strip()
return title, content
其中,我們使用了一個叫做get_chapter_content的函數來獲取每一個章節的標題和內容。在函數中,我們先發送一個請求,然後解析返回的html代碼,找到章節標題和內容所在的元素,並且將其文本內容提取出來。
四、存儲數據
最後,我們將獲取到的VIP文信息和章節內容保存到資料庫或者本地文件中。以下是將數據存儲到本地文件中的代碼:
with open('novel_list.txt', 'a', encoding='utf-8') as f:
for novel in novel_list:
f.write('小說名稱:{}\n作者:{}\n分類:{}\n簡介:{}\n鏈接:{}\n\n'.format(
novel['name'], novel['author'], novel['category'], novel['introduction'], novel['url']))
with open('chapter_content.txt', 'a', encoding='utf-8') as f:
for novel in novel_list:
for i, chapter in enumerate(chapters[novel['url']]):
title, content = get_chapter_content(chapter['url'])
f.write('小說名稱:{} 章節標題:{} 序號:{}\n內容:{}\n\n'.format(
novel['name'], title, i+1, content))
我們將VIP文列表信息保存到novel_list.txt文件中,將每一個章節的標題、內容、所屬小說名稱以及序號保存到chapter_content.txt文件中。
五、總結
本文詳細闡述了如何使用Python爬取晉江文學城中的VIP文。我們通過訪問VIP文列錶鏈接來獲取VIP文的基本信息,然後通過VIP文鏈接獲取每個章節的內容。最後,我們將獲取到的數據保存到本地文件中。
原創文章,作者:LHOXK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/374758.html