用Python3写一个遍历指定网站所有页面的爬虫 网址:httphouhuayuanvip需要的数据为章节名章节内容章节作者章节标签章节链接然后将全部数据保存至本地并生成目录并给出代码
由于本爬虫需要遍历整个网站,所以需要考虑网站的结构和页面链接的规律。通过观察目标网站,可以发现其章节页的链接形式为"http://houhuayuan.vip/小说名/章节编号.html",因此可以通过遍历小说名和章节编号来获取所有章节页面的链接。
以下是用Python3实现的爬虫代码,需要安装requests、BeautifulSoup和lxml库:
import os
import requests
from bs4 import BeautifulSoup
# 定义要遍历的网站及要爬取的小说名
base_url = 'http://houhuayuan.vip'
novel_name = 'xiyouji'
# 获取小说目录页
novel_catalog_url = f'{base_url}/{novel_name}/'
catalog_html = requests.get(novel_catalog_url).text
catalog_soup = BeautifulSoup(catalog_html, 'lxml')
# 获取小说名和章节数
novel_title = catalog_soup.h1.text.strip()
chapter_count = len(catalog_soup.select('div.list dd'))
# 遍历每个章节页面,获取数据并保存
novel_dir = f'{novel_title}({novel_name})'
if not os.path.exists(novel_dir):
os.mkdir(novel_dir)
with open(f'{novel_dir}/catalog.txt', 'w', encoding='utf-8') as catalog_file:
for i in range(1, chapter_count + 1):
chapter_url = f'{base_url}/{novel_name}/{i}.html'
chapter_html = requests.get(chapter_url).text
chapter_soup = BeautifulSoup(chapter_html, 'lxml')
# 获取章节名、内容、作者和标签
chapter_title = chapter_soup.h1.text.strip()
chapter_content = chapter_soup.select_one('div.content').text.strip()
chapter_author = chapter_soup.select_one('div.author').text.strip().split(':')[1]
chapter_tags = [tag.text for tag in chapter_soup.select('div.tag a')]
# 保存数据
with open(f'{novel_dir}/{i}.txt', 'w', encoding='utf-8') as chapter_file:
chapter_file.write(f'{chapter_title}\n\n')
chapter_file.write(f'{chapter_content}\n\n')
chapter_file.write(f'作者:{chapter_author}\n')
chapter_file.write(f'标签:{" / ".join(chapter_tags)}\n')
chapter_file.write(f'链接:{chapter_url}\n')
# 输出进度信息
print(f'已保存第{i}章:{chapter_title}')
# 写入目录文件
catalog_file.write(f'{i}. {chapter_title}\n')
本爬虫会先获取小说目录页,然后遍历所有章节页面获取数据并保存,最后生成目录文件。在保存数据时,章节名、作者和标签会写在文件头部,链接会写在文件尾部。在爬取过程中,会输出进度信息以便查看爬虫运行情况。
原文地址: https://www.cveoy.top/t/topic/bAbW 著作权归作者所有。请勿转载和采集!