本文共 1978 字,大约阅读时间需要 6 分钟。
本文将介绍如何使用Python编写一个爬取小说章节的脚本。以《冒牌大英雄》为例,讲述从非VIP章节爬取小说内容的实现方法。通过本地存储每个章节的内容,生成HTML格式的文件。
本次实现使用了以下技术和工具:
requests,用于发送HTTP请求,抓取网页内容完整的爬取流程如下:
使用requests库发送HTTP GET请求,获取起始网址的网页源代码。同时,设置合理的请求头信息,避免被网站反爬机制拦截。
import requestsimport reurl = 'https://book.qidian.com/info/131957'headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'accept-encoding': 'gzip, deflate, sdch, br', 'accept-language': 'zh-CN,zh;q=0.8'}response = requests.get(url, headers=headers)response.encoding = 'utf-8'response_text = response.text 网页源代码中通常嵌入了章节链接,可以通过正则表达式提取。常见的提取方式包括:
a标签li列表data-rid属性)pat = r''links = re.findall(pat, response_text)
对于每个找到的章节链接,重复以下步骤:
for link in links: # 发送请求获取章节内容 chapter_url = 'https://book.qidian.com' + link chapter_response = requests.get(chapter_url, headers=headers) chapter_response.encoding = 'utf-8' chapter_text = chapter_response.text # 提取标题和内容 title_pat = r'(.*?)
' content_pat = r'(?<=).*?(?=<\/content>)' title = re.search(title_pat, chapter_text).group(1) content = re.search(content_pat, chapter_text).group(0) # 保存文件 filename = f'"{title}"_{int(time.time())}.html' with open(filename, 'w', encoding='utf-8') as f: f.write(f' {title}
{content}')
为确保每个文件唯一,可以在标题中添加时间戳。这样即使同一标题的章节多次爬取,也能生成不同的文件名。
import timefilename = f'"{title}"_{int(time.time())}.html' requests库的timeout参数设置请求超时。通过以上方法,可以轻松实现爬取小说章节的需求。整个流程从获取源代码到存储本地文件,都可以通过Python脚本实现,满足批量处理和自动化的需求。
转载地址:http://kokr.baihongyu.com/