scrapy两种方法爬取网站小说

news/2024/5/12 8:57:55/文章来源:https://blog.csdn.net/qq_41346489/article/details/90678709

第一种,使用spider爬取

首先选择一个初始的小说链接,例如小说第一章的链接https://www.zwdu.com/book/11029/2297440.html
我爬去的是这个网站,链接中的小说
首先,创建一个项目

scrapy startproject novel
创建spider
scrapy genspider spider https://www.zwdu.com/book/11029/2297440.html
然后开始分析网站,因为该网站小说的链接没有规律,所以我选择通过下一页链接爬取下一章节的内容,然后到了最后一个章节发现最后的下一页链接不包含.html,可以设置一个if语句,来结束爬取。

这是下一章节链接在的地方。可以通过xpath来提取链接
在这里插入图片描述
这里是最后一章,链接不包括.html,可以用来作为停止爬取的条件
在这里插入图片描述
这里是我爬取的源码
spider.py

# -*- coding: utf-8 -*-
from scrapy import Request,Spider
import jsonclass SpiderSpider(Spider):name = 'spider'#allowed_domains = ['www.zwdu.com']start_urls = ['https://www.zwdu.com/book/26215/8210673.html']def parse(self, response):title = response.xpath("//h1/text()").extract_first()content = ''.join(response.xpath('//div[@id="content"]/text()').extract()).replace('    ', '\n')yield {'title':title,'content':content}next_url = response.xpath('//div[@class="bottem2"]/a[3]/@href').extract_first()base_url = 'https://www.81zw.com'+next_urlif next_url.find('.html') != -1:yield Request(base_url,callback=self.parse)

pipelines.py

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlclass XiaoshuoPipeline(object):def open_spider(self,spider):self.file = open('xiuzhen.txt','w',encoding='utf-8')def process_item(self, item, spider):title = item['title']content = item['content']info = title + '\n' + content + '\n'self.file.write(info)return itemdef close_spider(self,spider):self.file.close()

然后在settings中设置User-Agent,和ItemPipeline,执行scrapy crawl spider即可爬取这个小说。

第二种方法CrawlSpider

创建spider文件,scrapy genspider -t crawl example exampile.com
他使用Rule自动按规则提取链接进行爬取
在这里插入图片描述
LinkExtractor()有两个常用参数
allow:通过正则表达式来匹配
restrict_xpaths:通过xpath来匹配
因为crawlspider不会解析start_urls,所以需要从整个章节目录开始爬取,第一个Rule用来爬取第一章,第二个用来爬取接下来的每一章。解析方法和第一种方法一样,pipelines也不变。
spider2.py

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Ruleclass ZwwSpider(CrawlSpider):name = 'spider2'#allowed_domains = ['https://www.zwdu.com']start_urls = ['https://www.zwdu.com/book/11029/']rules = (Rule(LinkExtractor(restrict_xpaths=r'//*[@id="list"]/dl/dd[1]/a'), callback='parse_item', follow=True),Rule(LinkExtractor(restrict_xpaths=r'//div[@class="bottem1"]/a[3]'), callback='parse_item', follow=True),)def parse_item(self, response):title = response.xpath("//h1/text()").extract_first()content = ''.join(response.xpath('//div[@id="content"]/text()').extract()).replace('    ', '\n')yield {'title': title,'content': content}

pipelines.py

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlclass XiaoshuoPipeline(object):def open_spider(self,spider):self.file = open('xiuzhen.txt','w',encoding='utf-8')def process_item(self, item, spider):title = item['title']content = item['content']info = title + '\n' + content + '\n'self.file.write(info)return itemdef close_spider(self,spider):self.file.close()

settings.py

# -*- coding: utf-8 -*-# Scrapy settings for xiaoshuo project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.htmlBOT_NAME = 'xiaoshuo'SPIDER_MODULES = ['xiaoshuo.spiders']
NEWSPIDER_MODULE = 'xiaoshuo.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'# Obey robots.txt rules
ROBOTSTXT_OBEY = False# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 2
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default)
#COOKIES_ENABLED = False# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'xiaoshuo.middlewares.XiaoshuoSpiderMiddleware': 543,
#}# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {
#    'xiaoshuo.middlewares.XiaoshuoDownloaderMiddleware': 543,
# }# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'xiaoshuo.pipelines.XiaoshuoPipeline': 300,
}# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

以上就是两种爬取网站小说的方法,有不对的还请多多指教。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_903080.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

rhce:网络服务部分(三)给openlab搭建web网站

网站配置要求: 1.基于域名www.openlab.com可以访问网站内容为 welcome to openlab!!! 2.给该公司创建三个子界面分别显示学生信息,教学资料和缴费网站,基于www.openlab.com/student 网站访问学生信息,www.openlab.com/data网站访…

linux中搭建基于http协议静态网站

目录 一、搭建静态网站——基于http协议的静态网站 1.安装httpd,并将访问apache服务器的首页修改为hello.html, 且内容为: "My Home Page is hello" 2.虚拟主机:虚拟两台主机ip为100,200, 对应访问目录:/www/ip/100, /www/ip/200…

SERVLET+JSP实现网站登录和注册(初)

SERVLET 使用10.0tomcat导入SERVLET得用tomcat/lib里的servlet-api.jar <url-pattern>/myServlet</url-pattern> 拼接到 http://ip:port/工程路径即http://ip:port/工程路径/myServletjspservlet实现login和register 能传回来数据&#xff0c;login和regiser网页…

为openlab搭建web网站

准备工作 [rootlocalhost ~]# systemctl stop firewalld [rootlocalhost ~]# setenforce 0 [rootlocalhost ~]# yum install mod_ssl -y [rootlocalhost ~]# yum install httpd -y 一、基于域名www.openlab.com可以访问网站内容为welcome to openlab!!! 写入welcome to open…

网站基本配置表

网站的基本配置表 网站的基本参数 这些数据&#xff0c;不要单独放在各个表中&#xff0c; 要把所有参数放在网站中config表中&#xff0c;为网站运行的基本参数表

生成随机头像的网站

https://joeschmoe.io/api/v1/ 该网站为生成随机头像的网站 使用说明&#xff1a; ​ //每次访问该链接会生成随机头像 https://joeschmoe.io/api/v1/random​​//末尾的123可以改成其他数字&#xff0c;不同的数字能产生不同的头像&#xff0c; https://joeschmoe.io/api/v1…

四级,六级报名网站很卡怎么办?

报名四级&#xff0c;六级的同学总是遇到网站很卡的问题&#xff0c;要么加载不出来&#xff0c;就算等了好久加载出来了&#xff0c;稍微一操作&#xff0c;又变成白屏了。马上google一下&#xff0c;大多说505 HTTP Version Not Supported是由于服务器对http1.1协议不支持或者…

javaweb报错Connections could not be acquired from the underlying database,测试类可以通过,但是网站显示无法连接数据库

无法连接数据可的原因有很多&#xff1a; 1.检查jdbc.driver&#xff0c;jdbc.url&#xff0c;jdbc.username&#xff0c;jdbc.password是否配置错误 #若使用的mybatis版本是8.0以上的&#xff0c;则驱动器要加上cj jdbc.drivercom.mysql.cj.jdbc.Driver #如果使用的是MySQL8…

Web --- 电影网站

题目 代码 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>作业三</title><style>td{width: 80px;}img{width: 214.5px;height: 303.75px;}</style></head><body><div><div class…

大型网站架构之分布式消息队列

以下是消息队列以下的大纲&#xff0c;本文主要介绍消息队列概述&#xff0c;消息队列应用场景和消息中间件示例&#xff08;电商&#xff0c;日志系统&#xff09;。 本次分享大纲 消息队列概述消息队列应用场景消息中间件示例JMS消息服务常用消息队列参考&#xff08;推荐&…

个人网站搭建之快速入门

1. 写在前面 本文只是指导新手快速搭建一个简单的用于学习和自己玩的网站&#xff0c;预计完成时间1-2天&#xff0c;未考虑高并发、高可用、持续集成和运维运营等问题&#xff0c;适合于新手入门和学习&#xff0c;无需任何基础&#xff08;后面部署可能会需要一丢丢专业知识…

【开源探索】各种高仿网站合集

返回 CSDN目录 查看 github项目 1. 功能简述 仓库收集了近70热门网站的克隆高仿源码。包括Airbnb、亚马逊、抖音、Netflix、Youtube、Discord等。 当你看到抖音等的时候是不是想快速做个山寨的&#xff1f;又不想耗时耗力&#xff0c;这个项目是你绝佳的选择 2. 开源地址 …

Linux搭建web网站综合实验

网站需求&#xff1a; 1.基于域名[www.openlab.com](http://www.openlab.com)可以访问网站内容为 welcome to openlab!!! 2.给该公司创建三个子界面分别显示学生信息&#xff0c;教学资料和缴费网站&#xff0c;基于[www.openlab.com/student](http://www.openlab.com/studen…

渗透测试中如何辨别网站使用的脚本语言

判断网站使用的脚本语言也是信息收集的一部分&#xff0c;通过判断使用的何种脚本语言&#xff0c;来扩大攻击面。 asp asp本身并不是一种脚本语言&#xff0c;他只是提供了一种使镶嵌在HTML页面中的脚本程序得以运行的环境&#xff0c;ASP采用脚本语言VBScript(Java script)作…

微信扫码第三方登录,网站授权,redirect_url参数错误

最近在实现一个用微信扫码授权登录的项目&#xff0c;不是测试号&#xff0c;而是所有人都能登录&#xff0c;这就涉及到去微信开发平台申请应用了&#xff0c;具体的呢很多地方都有。 就是为了申请appid和AppSecret来进行实现&#xff0c; 废话不多说&#xff0c;很多人都遇…

小而美的博客网站-导入本地教程

前言&#xff1a; 在前人的基础上增加一些技术支持&#xff0c;便于在本地服务器使用&#xff0c;如需实现部署与上线&#xff0c;请百度。 第一步 下载 下载源码到本地&#xff0c;这个可以百度或者私聊我 第二步 导入 导入IDEA工具 之后可能需要配置maven&#xff0c;j…

常见的网站架构类型

0x01 简介 常见的服务器操作系统&#xff1a; Window --- Windows ServerLinux --- Cent OSUNIX --- HP-UX和IBM AIX&#xff0c;主要应用于金融证券等行业用户 在平台下架设Web服务器软件&#xff1a;Windows附带的IIS、Apache、Nginx 0x02 几款服务器 IIS&#xff1a;In…

tp3.23网站技术文件静态缓存,生成静态页面,计数器,定时操作生成静态页面和备份数据库

1&#xff0c;关于文件的静态缓存tp3有内置的F方法。 F方法他在公共函数库文件function.php里面 格式如下&#xff1a; /*** 快速文件数据读取和保存 针对简单类型数据 字符串、数组* param string $name 缓存名称* param mixed $value 缓存值* param string $path 缓存路径* …

史上最详细的网站优化系列(一)mysql优化1

一、mysql优化概述 方针&#xff1a; ① 存储层&#xff1a;数据表”存储引擎”选取、字段类型选取、逆范式(3范式) ② 设计层&#xff1a;索引、分区/分表、存储过程&#xff0c;sql语句的优化 ③ 架构层&#xff1a;分布式部署(集群)(读写分离)&#xff0c;需要增加硬件 ④ …

javaweb实现记单词网站

文章目录 记单词网站设计文档1.背景2.系统功能的设计2.1功能需求2.2数据库表设计2.3实体类的设计2.4实现各个模块流程图 3.实现3.1技术栈3.2项目结构3.3接口设计 4.效果 记单词网站设计文档 1.背景 下学期就要考四级了&#xff0c;就想自己设计一个可以记单词的程序&#xff…