用python爬小说_使用python+Scrapy爬小说

44079f58b10a

图片来源网络

写在前面

最近在学习python,不得不说python真是好用,至少生成程序的速度快,语法也比较简单 ヾ(◍°∇°◍)ノ゙

感觉很强大,之前怎么就没有想到学一下这个呢,如果大学抢课的时候用python写一个简单的程序,就不用好几天守在电脑前了 (T▽T)

之前写了一篇博文《使用python+selenium爬小说》,用的是Web的UI自动化测试框架selenium,这次用框架Scrapy爬小说

目标网站

44079f58b10a

网站截图

爬小说思路

1、创建保存小说的文件夹。路径为D:\shortNovel\

2、获取当前页面的所有小说标题、小说链接

3、获取每篇小说的章节名称、章节链接

4、获取每个章节的内容,将内容保存到对应的txt文件中

5、判断小说列表页面是否有下一页,如果有,则转到下一页,然后进行2的步骤

注意点

执行代码过程中,发现一篇小说的章节是乱序的,这个和scrayp的异步请求有关系,为了保证小说的章节是有序的,在settings.py做如下的配置,设置请求的数量为1

# Configure maximum concurrent requests performed by Scrapy (default: 16)

CONCURRENT_REQUESTS = 1

编写代码

1、项目生成

使用命令scrapy startproject shortNovel生成项目shortNovel

F:\python>scrapy startproject shortNovel

New Scrapy project 'shortNovel', using template directory 'i:\\users\\dengdai68\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\scrapy\\templates\\project', created in:

F:\python\shortNovel

You can start your first spider with:

cd shortNovel

scrapy genspider example example.com

2、参考代码

在shortNovel的spider文件夹中,新建文件shortNovelSpider.py。内容如下

#coding=utf-8

import scrapy

from scrapy.http import Request

import os

class shortNovelSpider(scrapy.Spider):

page = 2

name = 'shortNovel'

allowed_domains = ['qidian.com']

dirPath = 'D:\\shortNovel\\'

path=dirPath.strip()

path=path.rstrip("\\")

if not os.path.exists(path):

os.makedirs(path)

novelTitle = []

novelLink = []

url = 'https://www.qidian.com/free/all'

def getPageNovel():

pass

def start_requests(self):

yield Request(self.url, self.parse_novels)

def parse_novels(self, response):

novelLink = []

novelTitle = response.xpath('//*[@id="free-channel-wrap"]/div/div/div[2]/div[2]/div/ul/li/div/h4/a/text()').extract()

novelLink = response.xpath('//*[@id="free-channel-wrap"]/div/div/div[2]/div[2]/div/ul/li/div/h4/a/@href').extract()

#print (novelTitle)

#print (novelLink)

#len(novelLink)

#获取小说列表

for i in range(len(novelLink)):

file = open(self.dirPath+novelTitle[i]+'.txt','a+')

file.write(novelTitle[i])

file.write('\n')

file.close()

novelLink[i] = 'https:'+novelLink[i]+'#Catalog'

yield Request(novelLink[i], callback=self.parse_novel)

#下一页

nextPageList = response.xpath('//*[@id="page-container"]/div/ul/li/a/text()').extract()

nextPageLink = response.xpath('//*[@id="page-container"]/div/ul/li/a/@href').extract()

print(nextPageList)

nextLink = ''

for i in range(len(nextPageList)):

if nextPageList[i] == str(self.page):

self.page = self.page + 1

nextLink = 'https:'+nextPageLink[i]

break

yield Request(nextLink, callback=self.parse_novels)

def parse_novel(self, response):

chaptersTitle = []

chaptersLink = []

reqs = []

chaptersTitle = response.xpath('//*[@id="j-catalogWrap"]/div[2]/div/ul/li/a/text()').extract()

chaptersLink = response.xpath('//*[@id="j-catalogWrap"]/div[2]/div/ul/li/a/@href').extract()

#print (chapters)

#获取每一章节

for link in reversed(chaptersLink):

link = 'https:'+link

yield Request(link, callback=self.parse_chapter)

def parse_chapter(self, response):

novelName = response.xpath('//*[@class="act"]/text()').extract()[0]

chapterName = response.xpath('//*[@class="j_chapterName"]/text()').extract()

chapterText = response.xpath('//*[@class="read-content j_readContent"]//p/text()').extract()

file = open(self.dirPath+novelName+'.txt','a+')

file.write(chapterName[0])

file.write('\n')

for itext in range(len(chapterText)):

file.write(chapterText[itext])

file.write('\n')

file.close()

运行结果

执行命令scrapy crawl shortNovel,结果如下

44079f58b10a

执行结果

写在最后

1、这次使用的是scrapy框架,运行效果不错,爬取的速度比使用selenium快很多

2、使用上面的代码时要注意自己的磁盘空间,因为执行到最后是把每一页的小说爬下来,如果只要第一页,可以注释了以下代码

#下一页

nextPageList = response.xpath('//*[@id="page-container"]/div/ul/li/a/text()').extract()

nextPageLink = response.xpath('//*[@id="page-container"]/div/ul/li/a/@href').extract()

print(nextPageList)

nextLink = ''

for i in range(len(nextPageList)):

if nextPageList[i] == str(self.page):

self.page = self.page + 1

nextLink = 'https:'+nextPageLink[i]

break

yield Request(nextLink, callback=self.parse_novels)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值