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

yipeiwu_com5年前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抓取天猫商品详细信息及交易记录的具体代码,供大家参考,具体内容如下 一、搭建Python环境 本帖使用的是Python 2.7 涉及到的模块:spynne...

Python爬取qq空间说说的实例代码

具体代码如下所示: #coding:utf-8 #!/usr/bin/python3 from selenium import webdriver import time impo...

Python使用Beautiful Soup包编写爬虫时的一些关键点

1.善于利用soup节点的parent属性 比如对于已经得到了如下html代码: <td style="padding-left:0" width="60%"><l...

python2使用bs4爬取腾讯社招过程解析

目的:获取腾讯社招这个页面的职位名称及超链接 职位类别 人数 地点和发布时间 要求:使用bs4进行解析,并把结果以json文件形式存储 注意:如果直接把python列表没有序列化为jso...

Python实现多线程抓取妹子图

心血来潮写了个多线程抓妹子图,虽然代码还是有一些瑕疵,但是还是记录下来,分享给大家。 Pic_downloader.py # -*- coding: utf-8 -*- """ Cr...