Python实现的爬取小说爬虫功能示例

yipeiwu_com6年前Python爬虫

本文实例讲述了Python实现的爬取小说爬虫功能。分享给大家供大家参考,具体如下:

想把顶点小说网上的一篇持续更新的小说下下来,就写了一个简单的爬虫,可以爬取爬取各个章节的内容,保存到txt文档中,支持持续更新保存。需要配置一些信息,设置文档保存路径,书名等。写着玩,可能不大规范。

# coding=utf-8
import requests
from lxml import etree
from urllib.parse import urljoin
import re
import os
# 获取页面,并返回解析整理好的文本
def get_page(url):
  response = requests.get(url, headers=header)
  set_encoding(response)
  text = parse_page(response.text)
  return text
# 解析页面,将当前页面中的文字筛选出来
def parse_page(html):
  title = re.findall('<div class="bookname">\s+<h1>(.+?)</h1>', html)[0]
  content = re.findall('div id="content">(.*?)</div>', html, re.S)[0]
  content = content.replace('<br />', '').replace(' ', ' ').replace('\r\n\r\n', '\r\n')
  content = title + '\r\n' + content + '\r\n\r\n'
  return content
# 将文本追加到file_path对应的txt中
def save_page(path, text):
  with open(path, 'a', encoding='utf-8') as f:
    f.write(text)
# 设置对response得到文本的解析编码为'gbk'
def set_encoding(response):
  response.encoding = 'gbk'
# 从配置文件中获取当前保存的链接总数
def get_current_chapters_count(path):
  # (1)第一次读配置文件可能没有创建,所以要支持没有文件创建文件的功能(2)如果文件存在,则不能清空,参考/post/158740.htm
  with open(path, 'a+') as f:
    f.seek(0)
    res = f.read()
    if res == '':
      return 0
    else:
      return int(res)
# 将保存的链接总数保存到配置文件中
def set_current_chapters_count(path, count):
  with open(path, 'w') as f:
    f.write(str(count))
# 需要配置的字典
config_dic = dict(start_url='http://www.booktxt.net/2_2220/', # 待下载小说的章节首页 
         latest_item=9, # 列出的所有章节链接中,前面几个链接为最新章节,一般为9个,爬取时避免与最后部分重复,所以前面9个链接不爬取
         bookname='赘婿', # 待下载的小说名 
         folder_path='D:\\') #保存位置
domain = 'http://www.booktxt.net' # 顶点网域名
if __name__ == '__main__':
  chapter_url_list = []
  response = requests.get(config_dic['start_url'], headers=header)
  set_encoding(response)
  html = etree.HTML(response.text)
  chapters = html.xpath('//dd')
  print('所有链接' + str(len(chapters)))
  chapters = chapters[config_dic['latest_item']:] # 前9章为最新章节,后面还会重复,这里去掉
  print('不重复有效章节链接' + str(len(chapters)))
  folder_path = config_dic['folder_path'] + config_dic['bookname']
  if not os.path.exists(folder_path):
    os.mkdir(folder_path)
  file_path = folder_path + '\\' + config_dic['bookname'] + '.txt'
  config_file_path = folder_path + '\\' + 'config.txt'
  print('小说存储路径为:' + file_path)
  print('配置文件存储路径为:' + config_file_path)
  saved_count = get_current_chapters_count(config_file_path) # 获取目前保存的小说中已经包含的章节数
  print('当前' + file_path + '中已经保存的章节总数' + str(saved_count))
  if saved_count < len(chapters): # 说明有更新
    set_current_chapters_count(config_file_path, len(chapters))
    print('共更新 ' + str(len(chapters) - saved_count) + ' 章')
    for c in chapters[saved_count:]: # 从上次保存的位置开始继续保存
      url = c.xpath('a/@href')[0]
      url = urljoin(domain, url)
      txt = c.xpath('a/text()')[0]
      chapter_url_list.append(url)
      print(url)
      print(txt)
      save_page(file_path, get_page(url))
  else:
    print('小说还没有更新哦')

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python爬取指定微信公众号文章

本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下 该方法是依赖于urllib2库来完成的,首先你需要安装好你的python环境,然后安装urllib...

python通过伪装头部数据抵抗反爬虫的实例

0x00 环境 系统环境:win10 编写工具:JetBrains PyCharm Community Edition 2017.1.2 x64 python 版本:python-3.6...

Python使用Srapy框架爬虫模拟登陆并抓取知乎内容

Python使用Srapy框架爬虫模拟登陆并抓取知乎内容

一、Cookie原理 HTTP是无状态的面向连接的协议, 为了保持连接状态, 引入了Cookie机制 Cookie是http消息头中的一种属性,包括: Cookie名字(Name)...

scrapy爬虫完整实例

本文主要通过实例介绍了scrapy框架的使用,分享了两个例子,爬豆瓣文本例程 douban 和图片例程 douban_imgs ,具体如下。 例程1: douban 目录树 doub...

搞定这套Python爬虫面试题(面试会so easy)

搞定这套Python爬虫面试题(面试会so easy)

先来一份完整的爬虫工程师面试考点: 一、 Python 基本功 1、简述Python 的特点和优点 Python 是一门开源的解释性语言,相比 Java C++ 等语言,Python...