python 爬取小说

Python爬虫小说教程

 python 脚本爬取注意点

  1. 每个网站html的代码都不相同,需要自己分析结构,自己写xpath 的匹配代码去获取相应章节目录和章节内容;
  2. 小说涉及到文件,文件就要涉及编码,有时候出现编码问题,自己查着去解决
  3. 该脚本需要 requests 和 lxml 库, python 用pip 去安装 
  4. 该脚本是用 python 2 编码的, 所以用python 3 运行可能出现一些 语法问题,如 print "blog"; 在python2 可运行,python 3 必须用python("blog")
#-*- coding:utf-8
import os
import requests
from lxml import etree

#-*- 如果想获取 其他网站的小说,只需自己改动  xpath 的匹配代码

def requestHtml(url,tryTimes=1):  #通过网址 获取对应网页的html 源代码
  try:
    r=requests.get(url,timeout=30)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    print url
    return r.text
  except:
    if(tryTimes<5):               #获取失败之后是否重新获取,三次机会
      return requestHtml(url,tryTimes+1)
    else:
      print "requestHtml() have a error"
      return ""


def parseChapters(url):           #获取对应网页的小说章节 ,网址必须是https://www.2kxs.com/的小说对应的小说章节页面
  htmlCode=requestHtml(url)       
  html=etree.HTML(htmlCode)
  chapters=html.xpath("//dd[position()>4]/a/text()")
  hrefs=html.xpath("//dd[position()>4]/a/@href")
  return chapters,hrefs


def parseContent(url):           #获取对应网页的小说正文部分 ,网址必须是https://www.2kxs.com/的小说对应的小说的阅读页面
  htmlCode=requestHtml(url)
  html=etree.HTML(htmlCode)
  content=html.xpath("//child::p[2]/text()[position()>2]")
  txt=""
  for i in content:
    txt+=i+"\n"
  return txt

def autoParseTxt(url,txtName):  #自动生成对应的txt小说文档 
  chapters, urls = parseChapters(url)
  txtContext=""
  for i in range(len(urls)):
    content=parseContent(url+urls[i])
    txtContext+="#"+chapters[i]+"#\n"+content
    print i*1.0/len(urls)*100,"%"
  file=open(txtName+".txt","w")
  file.write(txtContext.encode("utf-8"))


def main():
  url="https://www.2kxs.com/xiaoshuo/106/106674/"  #小说章节目录
  txtName="zuiqiangfantaoluxitong"                 #小说生成txt的名字
  autoParseTxt(url,txtName)             


if __name__ == '__main__':
  main()


 

生成的 txt文件(可以直接用小说阅读app区直接阅读) 

平时看小说基本三种途径

  1. 小说网站  (免费,容易找,但有大量广告,小说字体大小和种类以及背景颜色效果都不如手机app的好用)
  2. 手机  (一般收费,但效果较好)
  3. 自己下载txt全集小说(不好找)

------------------------------------------------------------------------------​​​​​​​------------------------------------------------------------------------------

作为一个码农,还是自己需要啥,自己去搞, 小说自己爬取, 阅读软件自己去做!!

 

<think>为了爬取小说,我们需要选择一个小说网站,并分析其页面结构。这里以“笔趣阁”为例(注意:请确保遵守网站的使用条款,爬虫仅用于学习目的,且不要对网站造成过大压力)。 步骤: 1. 确定要爬取小说目录页URL。 2. 获取目录页的HTML,解析出所有章节的链接。 3. 遍历每个章节链接,获取章节内容。 4. 将章节内容保存到本地文件中。 我们将使用requests获取网页,使用BeautifulSoup解析HTML。 注意:有些网站有反爬机制,可能需要设置请求头(User-Agent)等。 示例:爬取《斗破苍穹》在笔趣阁中的小说。 假设目录页URL:`http://www.biquge.com.tw/0_1/` 由于网站可能变化,以下代码仅作为示例,实际使用时需要根据目标网站结构调整。 我们将: - 定义函数获取网页内容。 - 解析目录页,得到章节链接列表。 - 遍历每个章节,获取章节标题和正文。 - 将每个章节写入一个文本文件。 注意:为了避免请求过快被屏蔽,我们在每个请求之间加入短暂的延迟。 代码实现:</think>### Python爬取小说解决方案 我将使用`requests`获取网页内容,`BeautifulSoup`解析HTML,并添加反爬虫措施(随机User-Agent和延迟)。以下是完整代码: ```python import requests from bs4 import BeautifulSoup import time import random import re from fake_useragent import UserAgent def get_novel_content(novel_url): """爬取小说内容并保存到本地""" # 设置随机User-Agent ua = UserAgent() headers = {'User-Agent': ua.random} try: # 获取目录页 response = requests.get(novel_url, headers=headers, timeout=10) response.encoding = 'utf-8' soup = BeautifulSoup(response.text, 'html.parser') # 解析小说标题 novel_title = soup.find('h1').text.strip() print(f"开始爬取: 《{novel_title}》") # 解析章节链接 chapter_links = [] for link in soup.select('.listmain a'): if 'href' in link.attrs and '章' in link.text: chapter_links.append({ 'title': link.text.strip(), 'url': requests.compat.urljoin(novel_url, link['href']) }) # 创建保存文件 filename = f"{novel_title}.txt" with open(filename, 'w', encoding='utf-8') as f: f.write(f"《{novel_title}》\n\n") # 遍历所有章节 for i, chapter in enumerate(chapter_links): try: # 随机延迟防止被封(1-3秒) time.sleep(random.uniform(1, 3)) # 获取章节内容 chap_res = requests.get( chapter['url'], headers={'User-Agent': ua.random}, timeout=10 ) chap_res.encoding = 'utf-8' chap_soup = BeautifulSoup(chap_res.text, 'html.parser') # 提取正文内容 (根据网站结构调整选择器) content_div = chap_soup.select_one('#chaptercontent, .content, .novelcontent') if not content_div: print(f"警告: 未找到 {chapter['title']} 的正文") continue # 清理无用标签和广告 for tag in content_div.select('script, .adsbygoogle'): tag.decompose() # 处理文本格式 content = content_div.text.strip() content = re.sub(r'\s+', '\n', content) # 合并多余空白 content = re.sub(r'[\u3000]+', ' ', content) # 替换全角空格 # 写入文件 f.write(f"第{i+1}章 {chapter['title']}\n\n") f.write(content + "\n\n") f.flush() # 实时写入 print(f"已完成: {chapter['title']} ({i+1}/{len(chapter_links)})") except Exception as e: print(f"章节 {chapter['title']} 获取失败: {str(e)}") print(f"\n爬取完成! 文件已保存为: {filename}") return filename except Exception as e: print(f"爬取失败: {str(e)}") return None if __name__ == "__main__": # 示例URL (替换为目标小说目录页) novel_url = "https://www.biqg.cc/book/1/" get_novel_content(novel_url) ``` ### 代码详解 1. **反爬虫措施**: - `UserAgent().random`:每次请求使用随机User-Agent - `time.sleep(random.uniform(1, 3))`:章节间随机延迟 - `timeout=10`:设置请求超时 2. **核心功能**: - 目录页解析:通过CSS选择器`.listmain a`获取章节链接 - 内容清洗:删除广告标签(`script, .adsbygoogle`),正则表达式清理空白字符 - 编码处理:强制使用UTF-8编码防止乱码 3. **文件处理**: - 实时写入并`flush()`:防止意外中断丢失数据 - 章节标题编号:自动添加章节序号 4. **错误处理**: - 章节级异常捕获:单章失败不影响整体流程 - URL拼接:`urljoin`处理相对路径链接 ### 使用说明 1. 安装依赖: ```bash pip install requests beautifulsoup4 fake-useragent ``` 2. 修改目标URL: ```python novel_url = "https://www.example.com/novel/" # 替换为实际小说目录页 ``` 3. 常见网站适配调整: - **正文选择器**:修改`#chaptercontent`为目标网站的正文容器选择器 - **章节过滤**:修改`'章' in link.text`为实际章节标识 > ⚠️ 注意:请遵守目标网站的`robots.txt`规定,仅用于个人学习,避免高频访问造成服务器压力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值