Python爬取极品戒指小说并按章节保存
由于该网站可能存在反爬虫机制,建议先查看该网站的robots.txt文件,了解哪些页面可以爬取。
以下是一个简单的爬虫程序,通过requests和BeautifulSoup库来实现:
import requests
from bs4 import BeautifulSoup
# 请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
# 要爬取的小说主页
url = 'https://www.biqugemm.com/13_13743/'
# 发送请求
response = requests.get(url, headers=headers)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取小说名
title = soup.find('div', class_='bookname').h1.text
# 获取章节列表
chapter_list = soup.find('div', id='list').find_all('a')
# 循环爬取每一章节
for chapter in chapter_list:
# 获取章节名和链接
chapter_name = chapter.string
chapter_url = url + chapter.get('href')
# 发送请求
chapter_response = requests.get(chapter_url, headers=headers)
# 解析HTML
chapter_soup = BeautifulSoup(chapter_response.text, 'html.parser')
# 获取章节内容
content = chapter_soup.find('div', id='content').text
# 写入文件
with open(title + '.txt', 'a', encoding='utf-8') as f:
f.write(chapter_name + '\n')
f.write(content + '\n\n')
上述程序会将小说每一章节的内容保存在以小说名为文件名的txt文件中,每一章节的内容之间以两个换行符分隔。
原文地址: https://www.cveoy.top/t/topic/ovzZ 著作权归作者所有。请勿转载和采集!