Python爬虫学习笔记(十三)————CrawlSpider

news2024/11/26 3:48:16

目录

1.CrawlSpider介绍

2.使用方法

(1)提取链接

(2)模拟使用

(3)提取连接

(4)注意事项

3.运行原理

4.Mysql

5.pymysql的使用步骤

6.数据入库

(1)settings配置参数

(2)管道配置

 7.CrawlSpider案例:读书网数据入库

(1)案例分析

(2)项目结构

(3)items.py文件

(4)middlewares.py文件

(5)pipelines.py文件

(6)settings.py文件

(7)read.py文件


1.CrawlSpider介绍

  • 继承自scrapy.Spider
  • CrawlSpider可以定义规则,再解析html内容的时候,可以根据链接规则提取出指定的链接,然后再向这些链接发送请求
  • 所以,如果有需要跟进链接的需求,意思就是爬取了网页之后,需要提取链接再次爬取,使用CrawlSpider是非常合适的

2.使用方法

(1)提取链接

                链接提取器,在这里就可以写规则提取指定链接

        scrapy.linkextractors.LinkExtractor(

                        allow = (),                         # 正则表达式 提取符合正则的链接

                        deny = (),                         # (不用)正则表达式 不提取符合正则的链接

                        allow_domains = (),         #(不用)允许的域名

                        deny_domains = (),         #(不用)不允许的域名

                        restrict_xpaths = (),         # xpath,提取符合xpath规则的链接

                        restrict_css = ()               # 提取符合选择器规则的链接

                        )

(2)模拟使用

                正则用法:  links1 = LinkExtractor(allow=r'list_23_\d+\.html')

                xpath用法:links2 = LinkExtractor(restrict_xpaths=r'//div[@class="x"]')

                css用法:    links3 = LinkExtractor(restrict_css='.x')

(3)提取连接

                link.extract_links(response)

(4)注意事项

        【注1】callback只能写函数名字符串, callback='parse_item'

        【注2】在基本的spider中,如果重新发送请求,那里的callback写的是 callback=self.parse_item

        【注3】follow=true 是否跟进 就是按照提取连接规则进行提取

3.运行原理

4.Mysql

(1)下载(https://dev.mysql.com/downloads/windows/installer/5.7.html)

(2)安装(https://jingyan.baidu.com/album/d7130635f1c77d13fdf475df.html)

5.pymysql的使用步骤

1.pip install pymysql

2.pymysql.connect(host,port,user,password,db,charset)

3.conn.cursor()

4.cursor.execute()

6.数据入库

(1)settings配置参数

                DB_HOST = '192.168.231.128'

                DB_PORT = 3306

                DB_USER = 'root'

                DB_PASSWORD = '1234'

                DB_NAME = 'test'

                DB_CHARSET = 'utf8'

(2)管道配置

from scrapy.utils.project import get_project_settings

import pymysql

class MysqlPipeline(object):

#__init__方法和open_spider的作用是一样的

#init是获取settings中的连接参数

        def __init__(self):

                settings = get_project_settings()

                self.host = settings['DB_HOST']

                self.port = settings['DB_PORT']

                self.user = settings['DB_USER']

                self.pwd = settings['DB_PWD']

                self.name = settings['DB_NAME']

                self.charset = settings['DB_CHARSET']

                self.connect()

# 连接数据库并且获取cursor对象

        def connect(self):

                self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.pwd, db=self.name, charset=self.charset)

                self.cursor = self.conn.cursor()

        def process_item(self, item, spider):

                sql = 'insert into book(image_url, book_name, author, info) values("%s", "%s", "%s", "%s")' % (item['image_url'], item['book_name'], item['author'], item['info'])

                sql = 'insert into book(image_url,book_name,author,info) values ("{}","{}","{}","{}")'.format(item['image_url'], item['book_name'], item['author'], item['info'])

                # 执行sql语句

                self.cursor.execute(sql)

                self.conn.commit()

                return item

        def close_spider(self, spider):

                self.conn.close()

                self.cursor.close()

 7.CrawlSpider案例:读书网数据入库

(1)案例分析

1.创建项目:        scrapy startproject 项目的名字

2.跳转到spiders路径         cd 项目名字\项目名字\spiders

3.创建爬虫类:        scrapy genspider ‐t crawl read www.dushu.com

4.items

5.spiders

6.settings

7.pipelines

        数据保存到本地

        数据保存到mysql数据库

(2)项目结构

(3)items.py文件

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class ScrapyReadbook101Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    src = scrapy.Field()

(4)middlewares.py文件

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class ScrapyReadbook101SpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class ScrapyReadbook101DownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

(5)pipelines.py文件

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class ScrapyReadbook101Pipeline:

    def open_spider(self,spider):
        self.fp = open('book.json','w',encoding='utf-8')


    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item

    def close_spider(self,spider):
        self.fp.close()

# 加载settings文件
from scrapy.utils.project import get_project_settings
import pymysql


class MysqlPipeline:

    def open_spider(self,spider):
        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port =settings['DB_PORT']
        self.user =settings['DB_USER']
        self.password =settings['DB_PASSWROD']
        self.name =settings['DB_NAME']
        self.charset =settings['DB_CHARSET']

        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
                            host=self.host,
                            port=self.port,
                            user=self.user,
                            password=self.password,
                            db=self.name,
                            charset=self.charset
        )

        self.cursor = self.conn.cursor()


    def process_item(self, item, spider):

        sql = 'insert into book(name,src) values("{}","{}")'.format(item['name'],item['src'])
        # 执行sql语句
        self.cursor.execute(sql)
        # 提交
        self.conn.commit()


        return item


    def close_spider(self,spider):
        self.cursor.close()
        self.conn.close()

(6)settings.py文件

# Scrapy settings for scrapy_readbook_101 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'scrapy_readbook_101'

SPIDER_MODULES = ['scrapy_readbook_101.spiders']
NEWSPIDER_MODULE = 'scrapy_readbook_101.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'scrapy_readbook_101 (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# 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://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# 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://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'scrapy_readbook_101.middlewares.ScrapyReadbook101SpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'scrapy_readbook_101.middlewares.ScrapyReadbook101DownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}


# 参数中一个端口号 一个是字符集 都要注意
DB_HOST = '192.168.231.130'
# 端口号是一个整数
DB_PORT = 3306
DB_USER = 'root'
DB_PASSWROD = '1234'
DB_NAME = 'spider01'
# utf-8的杠不允许写
DB_CHARSET = 'utf8'




# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'scrapy_readbook_101.pipelines.ScrapyReadbook101Pipeline': 300,
   # MysqlPipeline
   'scrapy_readbook_101.pipelines.MysqlPipeline':301
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.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://docs.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'

(7)read.py文件

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from scrapy_readbook_101.items import ScrapyReadbook101Item


class ReadSpider(CrawlSpider):
    name = 'read'
    allowed_domains = ['www.dushu.com']
    start_urls = ['https://www.dushu.com/book/1188_1.html']

    rules = (
        Rule(LinkExtractor(allow=r'/book/1188_\d+.html'),
                           callback='parse_item',
                           follow=True),
    )

    def parse_item(self, response):

        img_list = response.xpath('//div[@class="bookslist"]//img')

        for img in img_list:
            name = img.xpath('./@data-original').extract_first()
            src = img.xpath('./@alt').extract_first()

            book = ScrapyReadbook101Item(name=name,src=src)
            yield book

 

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

uniapp使用

scroll-view封装tab组件 一个灵活的组件,可以自定义配置,,会设置一个 defaultConfig 去接收父组件传递的值去设置样式:比如 文字的颜色,激活文字的颜色,滑块的颜色,宽度,等滑块会跟着…

学习day51

几个注意点: 1.关于组件名: 一个单词组成: 第一种写法(首字母小写):school 第二种写法(首字母大写):School 多个单词组陈: 第一种写法(kebab-case…

基础算法(三)

目录 一、双指针算法 二、位运算 三、区间合并 一、双指针算法 双指针算法模板: for(int i 0,j 0;i < n;i) {while(j < i && check(i,j)) j;//每道题的具体逻辑 } 1.1两个指针指向两个队列1.2两个指针指向一个队列 案例习题: 分割字符串 #include<…

【C语言】自定义类型:结构体,枚举,联合

目录 前言&#xff1a;一.结构体1.结构体的声明2.结构体特殊的声明3.结构体的自引用4.结构体变量的定义和初始化5.结构体内存对齐6.修改默认对齐数7.结构体传参 二.位段1.什么是位段2.位段的内存分配 三.枚举1.枚举的定义2.枚举的优点 四.联合&#xff08;共用体&#xff09;1.…

php使用PDO_sqlsrv

php拓展下载&#xff1a;Microsoft Drivers for PHP 发行说明 - PHP drivers for SQL Server | Microsoft Learn 参考文章&#xff1a;php7.3.4 pdo方式连接sqlserver 设置方法_pdo sqlserver_黑贝是条狗的博客-CSDN博客 php5.6.9安装sqlsrv扩展&#xff08;windows&#xff0…

BEVDet 论文解读

BEVDet: High-Performance Multi-Camera 3D Object Detection in Bird-Eye-View 作者单位 PhiGent Robotics 目的 2D 的视觉感知在过去的几年里有了急速的发展&#xff0c;涌现出一些优秀的范式工作&#xff0c;这些工作有较高的性能&#xff0c;可扩展性&#xff0c;以及多…

【前端设计】使用Verdi查看波形时鼠标遮住了parameter值怎么整

盆友&#xff0c;你们在使用Verdi的时候&#xff0c;有没有遇到过鼠标遮挡着了parameter数值的场景&#xff1f;就跟下面这个示意图一样&#xff1a; 最可恨的是这个参数值他会跟着你的鼠标走&#xff0c;你想把鼠标移开看看看这个例化值到底是多大吧&#xff0c;这个数他跟着你…

云原生基础设施实践:NebulaGraph 的 KubeBlocks 集成故事

像是 NebulaGraph 这类基础设施上云&#xff0c;通用的方法一般是将线下物理机替换成云端的虚拟资源&#xff0c;依托各大云服务厂商实现“服务上云”。但还有一种选择&#xff0c;就是依托云数据基础设施&#xff0c;将数据库产品变成为云生态的一环&#xff0c;不只是提供自身…

直播回顾 | SDS 容灾方案,让制品数据更安全

7 月 18 日&#xff0c;腾讯云 CODING 与 XSKY星辰天合联合举办了主题为“SDS 容灾方案&#xff0c;让制品数据更安全”的线上研讨会。 来自腾讯云 CODING 的高级解决方案架构师陈钧桐和 XSKY星辰天合金融行业解决方案专家战策&#xff0c;分享了制品管理的困境与需求、腾讯云…

【数据挖掘】如何修复时序分析缺少的日期

一、说明 我撰写本文的目的是通过引导您完成一个示例来帮助您了解 TVF 以及如何使用它们&#xff0c;该示例解决了时间序列分析中常见的缺失日期问题。 我们将介绍&#xff1a; 如何生成日期以填补数据中缺失的空白如何创建 TVF 和参数的使用如何呼叫 TVF我们将考虑扩展我们的日…

Less知识点整理学习笔记

文章目录 1. Less介绍2. 安装2.1 部署node.js环境2.2 安装Less2.3 WebStorm配置Less 3. Less语法3.1 变量3.2 嵌套3.3 运算 1. Less介绍 Less是CSS预处理语言&#xff0c;可以使用变量、嵌套、运算等&#xff0c;便于维护项目CSS样式代码。 2. 安装 2.1 部署node.js环境 官…

Python爬虫学习笔记(十二)————scrapy案例

目录 1.yield 2.案例&#xff1a;当当网 3.案例&#xff1a;电影天堂 1.yield &#xff08;1&#xff09;带有 yield 的函数不再是一个普通函数&#xff0c;而是一个生成器generator&#xff0c;可用于迭代 &#xff08;2&#xff09; yield 是一个类似 return 的关键字&am…

《数据分析-JiMuReport07》JiMuReport报表开发-下拉框条数参数调整

JimuReport报表下拉框条数参数调整 {selectSearchPageSize:n} 1.下拉框条数限制 下拉框默认只显示10条记录&#xff0c;如果想要显示更多条数可以通过添加参数实现。 2.参数 selectSearchPageSize参数&#xff0c;设置参数大小 3.效果 可以看到设置的下拉框条数20条已经实现

细说小程序底部标签---【浅入深出系列006】

浅入深出系列总目录在000集 如何0元学微信小程序–【浅入深出系列000】 文章目录 本系列校训学习资源的选择 学习语法的前提底部标签的总概鹅厂的自定义标签官方说明&#xff1a; 先来了解app.json文件tabBar 位于app.json哪里 使用流程要注意的是&#xff1a;配套资源作业&a…

el-popover在原生table中,弹出多个以及内部取消按钮无效问题

问题&#xff1a;当el-popover和原生table同时使用的时候会失效&#xff08;不是el-table) <el-popover placement"bottom" width"500" trigger"click" :key"popover-${item.id}"></el-popover> 解决&#xff1a; :key…

虚拟数字人——NeRF实现实时对话数字人

前言 1.这是一个能实时对话的虚拟数字人demo,使用的是NeRF&#xff08;Neural Radiance Fields&#xff09;&#xff0c;训练方式可以看看我前面的博客。 2.文本转语音是用了VITS语音合成&#xff0c;项目git:https://github.com/jaywalnut310/vits . 3.语言模型是用了新开…

Jenkins从配置到实战(一) - 实现C/C++项目自动化编译

前言 本文章主要介绍了&#xff0c;如何去安装和部署Jenkins&#xff0c;并实现自动拉取项目代码&#xff0c;自动化编译流程。 网站 官网中文网站 下载安装 可以下载这个 安装jenkins前先安装java yum search java|grep jdkyum install java-1.8.0-openjdk 安装jenkins j…

NE555 PWM输出

NE555是一种集成电路&#xff08;IC&#xff09;&#xff0c;通常用于电子电路的各种目的&#xff0c;包括计时器、振荡器等等。 本文介绍搭建NE555电路输出PWM信号&#xff0c;电路如图下&#xff1a; 使用该电路可以输出PWM占空比≥50%波形&#xff0c;仿真波形如下图&#…

20230723在win10的命令行下显示文本文件的内容type

20230723在win10的命令行下显示文本文件的内容type 2023/7/23 20:35 百度搜索&#xff1a;WINDOWS 命令行 打开文本文件 windows命令行读取文件命令-WinFrom控件库|.net开源控件库... 2023年7月14日 linux下,可能会用到cat或都是more命令,windows下可以使用type或more命令 type…

VMware Fusion 14 Tech Preview - 适用于 Arm 的 Windows 11 上的全面 3D 加速

VMware Fusion 14 Tech Preview - 适用于 Arm 的 Windows 11 上的全面 3D 加速 VMware Fusion Tech Preview 2023 请访问原文链接&#xff1a;https://sysin.org/blog/vmware-fusion-14/&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页&#xff1a;…