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全集小说(不好找)

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

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

猜你喜欢

转载自blog.csdn.net/cout__waht/article/details/81812936