目录

  • 前言
  • 一、爬虫思路
  • 二、使用步骤
    • 1.引入库
    • 2.读取页面
    • 3.分析HTML
    • 3.从标签中取出信息
    • 4.爬取正文
  • 总结

前言

实习期间自学了vba,现在开始捡回以前上课学过的python,在此记录学习进程


本文内容仅用于学习,请勿商用

一、爬虫思路

无需登录的页面只需要用到简单爬虫,获取小说目录、通过目录获取小说正文即可。

二、使用步骤

1.引入库

代码如下(示例):

import requests,sys
from bs4 import BeautifulSoup

2.读取页面

代码如下(示例):

target = 'https://book.qidian.com/info/1024995653#Catalog'
req = requests.get(url=target)

为防止页面出错、页面乱码问题,分别加入:

req.raise_for_status()
req.encoding = req.apparent_encoding

此时即可看到网页HTML:

html = req.text

3.分析HTML

在HTML代码中,我们要找到对应目录的文字和链接,以及承载这两个信息的标签:

在小说目录页面按下F12,观察页面的HTML,可以发现目录是在一个class=‘catalog-content-wrap’、id=‘j-catalogWrap’的div标签下的。继续分析,发现还有volume-wrap,volume等子标签作为目录的容器:

一直向下延伸到带有链接的a标签,定位到目标,分析完毕。

bf = BeautifulSoup(html,"html.parser")
catalogDiv = bf.find('div',class_='catalog-content-wrap',id='j-catalogWrap')
volumeWrapDiv = catalogDiv.find('div',class_='volume-wrap')
volumeDivs = volumeWrapDiv.find_all('div',class_='volume')

3.从标签中取出信息

仍然是利用BS直接取出volume中所有的a标签,并且把其中的文本和对应的href存起来。

aList = volumeDiv.find_all('a')
for a in aList:chapterName = a.stringchapterHref = a.get('href')

这样整个目录就检索完成了,开始利用Href爬取正文。


4.爬取正文

先随便选择一个链接打开,观察正文的HTML:


发现格式会有两种情况,一种直接用p标签装起来,一种是p中带有span,用class=content-wrap的span装起来。
但是首先他们都一定是在class=‘read-content j_readContent’的div下,因此直接定位:

req = requests.get(url=chapterHref)
req.raise_for_status()
req.encoding = req.apparent_encoding
html = req.text
bf = BeautifulSoup(html,"html.parser")
mainTextWrapDiv = bf.find('div',class_='main-text-wrap')
readContentDiv = mainTextWrapDiv.find('div',class_='read-content j_readContent')
readContent = readContentDiv.find_all('span',class_='content-wrap')

这时已经可以拿到带有标签的正文部分了,由于链接不同,会导致标签格式不同,因此用判断区分:

if readContent == []:textContent = readContentDiv.text.replace('<p>','\r\n')textContent = textContent.replace('</p>','')
else:for content in readContent:if content.string == '':print('error format')else:textContent += content.string + '\r\n'

正文内容获取完毕。

现在只需遍历就能获取整部小说啦!

总结

以下为完整代码:

#!/usr/bin/env python3
# coding=utf-8
# author:sakuyo
#----------------------------------
import requests,sys
from bs4 import BeautifulSoupclass downloader(object):def __init__(self,target):#初始化self.target = targetself.chapterNames = []self.chapterHrefs = []self.chapterNum = 0self.session = requests.Session()def GetChapterInfo(self):#获取章节名称和链接req = self.session.get(url=self.target)req.raise_for_status()req.encoding = req.apparent_encodinghtml = req.textbf = BeautifulSoup(html,"html.parser")catalogDiv = bf.find('div',class_='catalog-content-wrap',id='j-catalogWrap')volumeWrapDiv = catalogDiv.find('div',class_='volume-wrap')volumeDivs = volumeWrapDiv.find_all('div',class_='volume')for volumeDiv in volumeDivs:aList = volumeDiv.find_all('a')for a in aList:chapterName = a.stringchapterHref = a.get('href')self.chapterNames.append(chapterName)self.chapterHrefs.append('https:'+chapterHref)self.chapterNum += len(aList)def GetChapterContent(self,chapterHref):#获取章节内容req = self.session.get(url=chapterHref)req.raise_for_status()req.encoding = req.apparent_encodinghtml = req.textbf = BeautifulSoup(html,"html.parser")mainTextWrapDiv = bf.find('div',class_='main-text-wrap')readContentDiv = mainTextWrapDiv.find('div',class_='read-content j_readContent')readContent = readContentDiv.find_all('span',class_='content-wrap')if readContent == []:textContent = readContentDiv.text.replace('<p>','\r\n')textContent = textContent.replace('</p>','')else:for content in readContent:if content.string == '':print('error format')else:textContent += content.string + '\r\n'return textContentdef writer(self, path, name='', content=''):write_flag = Truewith open(path, 'a', encoding='utf-8') as f: #a模式意为向同名文件尾增加文本if name == None:name=''if content == None:content = ''f.write(name + '\r\n')f.writelines(content)f.write('\r\n')if __name__ == '__main__':#执行层target = 'https://book.qidian.com/info/1024995653#Catalog'dlObj = downloader(target)dlObj.GetChapterInfo()print('开始下载:')for i in range(dlObj.chapterNum):try:dlObj.writer( 'test.txt',dlObj.chapterNames[i], dlObj.GetChapterContent(dlObj.chapterHrefs[i]))except Exception:print('下载出错,已跳过')passsys.stdout.write("  已下载:%.3f%%" %  float(i/dlObj.chapterNum) + '\r')sys.stdout.flush()print('下载完成')

Python简单爬取起点中文网小说(仅学习)相关推荐

  1. python爬虫之爬取起点中文网小说

    python爬虫之爬取起点中文网小说 hello大家好,这篇文章带大家来制作一个python爬虫爬取阅文集团旗下产品起点中文网的程序,这篇文章的灵感来源于本人制作的一个项目:电脑助手 启帆助手 ⬆是项 ...

  2. python 爬虫抓取网页数据导出excel_Python爬虫|爬取起点中文网小说信息保存到Excel...

    前言: 爬取起点中文网全部小说基本信息,小说名.作者.类别.连载\完结情况.简介,并将爬取的数据存储与EXCEL表中 环境:Python3.7 PyCharm Chrome浏览器 主要模块:xlwt ...

  3. Python爬虫爬取纵横中文网小说

    Python爬虫爬取纵横中文网小说 学了一周的爬虫,搞了这个东西,自己感觉还不错,有什么问题可以提一提哈 目标:纵横中文网-完本-免费小说 网址:http://book.zongheng.com/st ...

  4. python request 爬虫爬取起点中文网小说

    1.网页分析.进入https://www.qidian.com/,点击全部,进行翻页,你就会发现一个规律, url=https://www.qidian.com/all?orderId=&st ...

  5. python爬虫——爬取起点中文网作品信息

    首先打开起点中文网 点开红圈内的全部作品选项,本博客爬取这里面的作品信息. 接下来爬取所有作品信息,注意,不仅仅只是该面的所有作品信息,而是全部作品信息. 网页下面有跳转其他页的选项. 我们需要找到网 ...

  6. 爬取起点中文网小说介绍信息

    字数的信息(word)没有得到缺失 import xlwt import requests from lxml import etree import timeall_info_list=[] hea ...

  7. java爬虫抓取起点小说_爬虫实践-爬取起点中文网小说信息

    qidian.py: import xlwt import requests from lxml import etree import time all_info_list = [] def get ...

  8. Python爬虫之爬取起点中文网

    python之爬取起点中文网 最近学了爬虫,想实战一下就选取了最近经常看小说的起点中文网来进行爬取 过程如下: 分析爬取信息: 爬取网址:https://www.qidian.com/rank?chn ...

  9. Python爬虫爬取纵横中文网月票排行榜前1000的小说

    python爬虫学习 文章目录 前言 一.python爬虫 二.使用步骤 1.引入库 2.解析网页函数 3.获取数据函数 4.储存数据函数 5.主函数 6.创建全局变量 7.完整代码 8.爬虫实现 总 ...

最新文章

  1. xp系统蓝屏代码7b_电脑蓝屏重启不求人!学会这个方法,自己就能轻松解决!...
  2. DFS Gym 100553J Jokewithpermutation
  3. mysql 的connect 设置 无法点next_技术分享 | MySQL 使用 MariaDB 审计插件
  4. 中国半导体最强助攻来了!十年免税、上下游一揽子扶持,明确「集成电路」为一级学科...
  5. java 企业门户网站 源码 自适应响应式 freemarker 静态引擎 html5 SSM
  6. 【人物】养车点点费岸:给O2O产品经理的四点意见
  7. MyClass a,b[2],*p[2]调用了几次构造函数
  8. Java进阶:@FunctionalInterface函数式接口使用说明
  9. Iterator 遍历器的简单使用
  10. 多源异构数据_构建数字孪生城市的CIM数据平台哪家强?
  11. OpenSTA -- 开源测试工具软件
  12. 【数据结构与算法】算法的时间复杂度
  13. 收藏商品表设计_babycare商品价格及销售情况分析
  14. 计算机的桌面图标类型,软件图标的格式 电脑桌面图标是什么格式的文件啊
  15. 腾讯云服务器申请自助退款流程(图文教程)
  16. 一文读懂中国5G的真正实力
  17. python发邮件被认定为垃圾邮件_使用Python登陆QQ邮箱发送垃圾邮件 简单实现
  18. edge浏览器突然不能播放视频解决办法
  19. 3D目标检测-BEVFormer、BEVDepth
  20. Pr:抠像与视频合成

热门文章

  1. [ROS] sh脚本文件,source : not found问题
  2. 山特UPS不间断电源的主要技术参数
  3. (建议收藏)服务器宕机,效率排查攻略V2.0
  4. Kaggle实战:泰坦尼克幸存者预测 -下
  5. 我写了一套SpringBoot微信小程序电商全栈就业实战课程,免费分享给CSDN的朋友们
  6. 2198: 小P当志愿者送餐
  7. 从零开始写一个RPC框架的详细步骤
  8. html5绘制随机五角星_HTML5 canvas基本绘图之绘制五角星
  9. Java File文件流读取文件夹内的文件并替换文件内容
  10. 初中算题可以使用计算机吗,初中生计算机考试试题总汇