scrapy的入门

今天我们先学习一下scrapy的入门,Scrapy是一个快速的高层次的网页爬取和网页抓取框架,用于爬取网站并从页面中提取结构化的数据。

1. scrapy的概念和流程

1.1 scrapy的概念

我们先来了解一下scrapy的概念,什么是scrapy:

Scrapy是一个Python编写的开源网络爬虫框架。它是一个被设计用于爬取网络数据、提取结构性数据的框架。而框架就是把之前简单的操作抽象成一套系统,这样我们在使用框架的时候,它会自动的帮我们完成很多工作,我们只需要完成剩余部分

 Scrapy 使用了Twisted['twɪstɪd]异步网络框架,可以加快我们的下载速度。

Scrapy文档地址:http://scrapy-chs.readthedocs.io/zh_CN/1.0/intro/overview.html

1.2. scrapy框架的作用

 少量的代码,就能够快速的抓取 ,框架是代码的半成品,提高效率(爬虫效率和开发效率)

scrapy框架是一个用于网络爬虫的快速、高层次的框架,它提供了一套丰富的功能,使得从网站上抓取数据变得简单和高效。

1. 3. scrapy的工作流程:

上面的流程可以改写为

 scrapy的流程 (可以理解为是3.2流程的抽象化流程)

以下是完整的对这个过程的解释:

1. 爬虫中起始的url构造成request对象-->爬虫中间件-->引擎-->调度器

2. 调度器把request-->引擎-->下载中间件--->下载器

3. 下载器发送请求,获取response响应---->下载中间件---->引擎--->爬虫中间件--->爬虫

4. 爬虫提取url地址,组装成request对象---->爬虫中间件--->引擎--->调度器,重复步骤2

5. 爬虫提取数据--->引擎--->管道处理和保存数据


1.3.1初始请求

用户在Scrapy项目中定义起始URL(通常是在spiders目录下的某个Spider类中)。

这些URL被转换为Request对象,这些对象被发送到Scrapy引擎。

在发送到引擎之前,这些Request对象会经过爬虫中间件(如果有定义的话)进行处理。

1.3.2调度器(Scheduler) 

调度好的Request被再次发送给引擎。

调度器根据优先级、重复过滤等因素对Request进行排序和调度。

引擎将Request对象发送给调度器。

1.3.3下载中间件(Downloader Middlewares)

引擎将Request对象发送给下载中间件(如果有定义的话)。

下载中间件可以对Request对象进行额外的处理,比如添加请求头、设置代理等。

处理后的Request对象被发送到下载器(Downloader)。

1.3.4下载器(Downloader)

下载器负责发送HTTP请求到目标网站。

下载器接收响应(Response对象),并将其发送回引擎。

在返回给引擎之前,响应会经过下载中间件(如果有定义的话),以便进行额外的处理,比如处理cookies、重试失败的请求等

1.3.5爬虫(Spiders)

  • 引擎将Response对象发送给对应的爬虫。
  • 爬虫解析Response对象,提取数据(通常是使用XPath、CSS选择器或正则表达式)。
  • 爬虫还可以提取新的URL,并生成新的Request对象。
  • 这些新的Request对象会经过爬虫中间件(如果有定义的话)发送到引擎。

1.3.6重复步骤2-5

对于爬虫提取的新URL,流程会重复步骤2-5,直到没有更多的URL需要处理或者满足某个停止条件(比如达到最大请求数、达到某个时间限制等)。

1.3.7管道(Pipelines)

爬虫提取的数据被发送到Item Pipeline(如果有定义的话)。

Item Pipeline负责处理这些数据,比如验证数据的完整性、清理HTML标签、将数据保存到数据库或文件系统等。

处理后的数据最终会被保存或丢弃,具体取决于Item Pipeline的实现。

1.3.8注意:

图中中文是为了方便理解后加上去的

 图中绿色线条的表示数据的传递

 注意图中中间件的位置,决定了其作用

 注意其中引擎的位置,所有的模块之前相互独立,只和引擎进行交互

1.4scrapy的三个内置对象

1.4.1.request请求对象:

Request对象代表一个HTTP请求,由Scrapy下载器中间件发送到互联网并等待服务器的响应。 

  • 它通常包含以下属性:
    • url(字符串):请求的URL。
    • method(字符串):HTTP请求方法(如"GET"或"POST")。
    • headers(字典):一个字典,包含HTTP头及其值。
    • body(字节串):请求体,用于POST或PUT请求。
    • meta(字典):用于在Scrapy引擎内部传递信息的字典。
    • cookies(字典或CookieJar):与请求一起发送的cookies。
    • 其他可能用于特定目的的属性。

1.4.2.response响应对象:

由url body status headers等构成

Response对象包含服务器对Request的响应。

它通常包含以下属性:

  • url(字符串):响应的URL(可能与请求的URL不同,例如由于重定向)。
  • status(整数):HTTP状态码(如200表示成功)。
  • headers(字典):包含HTTP响应头的字典。
  • body(字节串):响应体,即服务器返回的数据。
  • meta(字典):与产生该响应的Request对象中的meta相同。
  • request(Request对象):产生此响应的Request对象。
  • 其他可能用于特定目的的属性。

Scrapy还提供了选择器(Selectors)来方便地从Response对象中提取数据,如XPath和CSS选择器。 

1.4.3.item数据对象:

本质是个字典

  • Item对象用于收集爬虫从网页中提取的数据。
  • 它本质上是一个简单的Python字典,但提供了额外的功能,如字段验证和清理。
  • 你可以通过定义自己的Item类来指定爬虫将收集哪些数据。
  • 例如,如果你正在编写一个爬取电商网站信息的爬虫,你可能会定义一个ProductItem类,该类包含namepricedescription等字段。

在Scrapy中,你通常会定义一个或多个Item类来表示你想要从网站提取的数据结构。然后,在你的爬虫代码中,你可以创建这些Item类的实例,并将提取的数据填充到这些实例中。最后,这些Item实例将被Scrapy的管道(Pipeline)系统处理,可能包括清洗、验证和存储到数据库等操作。

 1.5 scrapy中每个模块的具体作用

注意:爬虫中间件和下载中间件只是运行逻辑的位置不同,作用是重复的:如替换UA等

2. scrapy的入门使用:

2.1 安装scrapy:

直接cmd安装:pip/pip3 install scrapy  

(换源安装命令:pip install scrapy -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.comn )

安装依赖包:pip install pypiwin32

        如果不安装,以后的项目会报错

        window系统需要安装,Linux,Mac不需要

2.2 scrapy项目开发流程

2.2.1. 创建项目:

          scrapy startproject mySpider

2.2.2. 生成一个爬虫:

          scrapy genspider lianjia lianjia.com

2.2.3. 提取数据:

        根据网站结构在spider中实现数据采集相关内容

2.2.4. 保存数据:

        使用pipeline进行数据后续处理和保存

2.3. 创建项目:

通过命令将scrapy项目的的文件生成出来,后续步骤都是在项目文件中进行相关操作,下面以抓取链家来学习scrapy的入门使用

创建scrapy项目的命令:

scrapy startproject <项目名字>

示例:

        scrapy startproject myspider

2.4. 创建爬虫

通过命令创建出爬虫文件,爬虫文件为主要的代码文件,通常一个网站的爬取动作都会在爬虫文件中进行编写。

命令:

        **在项目路径下执行**:<br/>

        scrapy genspider <爬虫名字> <允许爬取的域名>

爬虫名字: 作为爬虫运行时的参数<br/>

允许爬取的域名:

为对于爬虫设置的爬取范围,设置之后用于过滤要爬取的url,如果爬取的url与允许的域不通则被过滤掉。

示例:

cd myspider       ***这一步是进入当前项目路径***

scrapy genspider lianjia lianjia.com        ***再创建爬虫文件***

2.4.1,scrapy.cfg

详细项目配置文件, 不需要做改动

2.4.2,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 MyspiderItem(scrapy.Item):
    # 实际是一个模板类(数据建模) 事先定义好你要爬取的字段
    name = scrapy.Field()  # 租房标题
    content = scrapy.Field() # 详情信息
    price = scrapy.Field()  # 价格
    link = scrapy.Field() # 详情链接

2.4.3,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 MyspiderSpiderMiddleware:
    # 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 MyspiderDownloaderMiddleware:
    # 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)

2.4.4,lianjia.py (爬虫文件,文件名称自己定义)  [后面再来完善该爬虫模块]

import scrapy

class LianjiaSpider(scrapy.Spider):
    # 爬虫名字
    name = 'lianjia'
    # 限定爬取的域名范围
    allowed_domains = ['cs.lianjia.com']
    # 起始请求的URL
    start_urls = ['https://cs.lianjia.com/zufang/']
    
    # 该方法会接受下载中间件传过来的response,并对其进行解析
    def parse(self, response):
        pass

2.4.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 MyspiderPipeline:
    def process_item(self, itemder):
        return item

2.4.6,settings.py   详细的配置信息(设置文件UA  并启动管道)

# Scrapy settings for mySpider 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 = 'mySpider'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
# 需要手动修改成自己浏览器的UA
USER_AGENT = 'mySpider (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False # 需要手动修改为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://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 = {
#    'mySpider.middlewares.MyspiderSpiderMiddleware': 543,
# }

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

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html

#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# 开启管道类才能写入数据
ITEM_PIPELINES = {
   'mySpider.pipelines.MyspiderPipeline': 300,
}

# 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'

2.5. 完善爬虫

在上一步生成出来的爬虫文件中编写指定网站的数据采集操作,实现数据提取

2.5.1 在/myspider/myspider/spiders/itcast.py中修改内容如下:

import scrapy
from mySpider.items import MyspiderItem

class LianjiaSpider(scrapy.Spider):
    # 爬虫名字
    name = 'lianjia'
    # 限定爬取的域名范围
    allowed_domains = ['cs.lianjia.com']
    # 起始请求的URL
    start_urls = ['https://cs.lianjia.com/zufang/']

    # 该方法会接受下载中间件传过来的response,并对其进行解析
    def parse(self, response):
        # print("响应对象:",response)  # response是一个响应对象
        # html_data = response.body  # 获取网页源码
        # print("源码信息:", html_data)
        # # 将获取回来的网页源码保存为本地html文件,方便做分析
        # with open('lj.html','wb')as f:
        #     f.write(html_data)
        # 正式解析想要的数据
        # 会返回一个为列表的Selector选择器对象
        # 将列表遍历成字符串再通过.extract()取选择器里的所有值,.extract_first()取出选择器里的第一个值
        name = response.xpath(
            '//div[@class="content__list--item--main"]//p[@class="content__list--item--title"]/a/text()').extract()
        price = response.xpath('//div[@class="content__list--item--main"]//em/text()').extract()
        link = response.xpath('//div[@class="content__list--item--main"]//a[@class="twoline"]/@href').extract()
        for names, prices, links in zip(name, price, link):
            # 创建一个数据字典
            # item = {}
            # 调用items模板类
            item = MyspiderItem()  #实例化之后可以直接使用 目前是一个空字典
            # 给实例之后的空字典组建数据 要注意得与items文件中定义的变量一致
            item["name"] = names.strip()
            item["price"] = prices
            item["link"] = "https://cs.lianjia.com/" + links
            # print(names.strip())
            # print(prices)
            # print("https://cs.lianjia.com/"+links)
            # print('=='*10)
            # print(item)
            
            # 将组建好的dict形式数据通过yield返回给引擎 再交给管道文件Pipeline
            yield item

注意:

- scrapy.Spider爬虫类中必须有名为parse的解析

- 如果网站结构层次比较复杂,也可以自定义其他解析函数

- 在解析函数中提取的url地址如果要发送请求,则必须属于allowed_domains范围内,但是start_urls中的url地址不受这个限制,我们会在后续的课程中学习如何在解析函数中构造发送请求

- 启动爬虫的时候注意启动的位置,是在项目路径下启动

- parse()函数中使用yield返回数据,

注意:解析函数中的yield能够传递的对象只能是:BaseItem, Request, dict, None

2.5.2 定位元素以及提取数据、属性值的方法

解析并获取scrapy爬虫中的数据: 利用xpath规则字符串进行定位和提取

1. response.xpath方法的返回结果是一个类似list的类型,其中包含的是selector对象,操作和列表一样,但是有一些额外的方法

2. 额外方法extract():返回一个包含有字符串的列表

3. 额外方法extract_first():返回列表中的第一个字符串,列表为空没有返回None

2.6 保存数据

 利用管道pipeline来处理(保存)数据

2. 6.1 在pipelines.py文件中定义对数据的操作

1. 定义一个管道类

2. 重写管道类的process_item方法

3. process_item方法处理完item之后必须返回给引擎

# 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
import json

from itemadapter import ItemAdapter

class MyspiderPipeline:
    def __init__(self):
        self.file = open('lianjia.json','w')

    # 爬虫文件中提取数据的方法每yield一次item,就会运行一次
    # 该方法为固定名称函数
    def process_item(self, item, spider):
        # 参数item默认是一个 <class 'mySpider.items.MyspiderItem'>类信息,需要处理成字典
        dict_data = dict(item)
        print(type(item), type(dict_data))
        # 将返回的字典数据转为JSON数据
        json_data = json.dumps(dict_data,ensure_ascii=False)+',\n'
        # 写入JSON数据
        self.file.write(json_data)
        # 参数item:是爬虫文件中yield的返回的数据对象(引擎会把这个交给管道中的这个item参数)
        print("建模之后的返回值:",item,)
        # 默认使用完管道之后将数据又返回给引擎
        return item

    def __del__(self):
        self.file.close()

2. 6.2 在settings.py配置启用管道

#   设置目录文件               该值的大小决定管道执行的顺序,值越小优先级越高(该值最好 不要大于1000)  

ITEM_PIPELINES = {

   'mySpider.pipelines.MyspiderPipeline': 300,

}

以上配置项中键为使用的管道类,管道类使用.进行分割,第一个为项目目录,第二个为文件,第三个为定义的管道类。

配置项中值为管道的使用顺序,设置的数值约小越优先执行,该值一般设置为1000以内。

2.7. 运行scrapy

命令:在项目目录下执行scrapy crawl <爬虫名字>

示例:scrapy crawl 爬虫名字 --nolog 忽略日志信息

2.7.1  也可爬虫项目中执行命令

每次我们写完代码进行测试的时候,都要去安装目录执行,所以为了方便,我们要写一个再爬虫项目根目录中创建.py结尾的文件,执行以下指令:

from scrapy import cmdline
cmdline.execute(['scrapy','crawl','lianjia'])

2. 8,Scrapy Shell的使用

我们想要爬虫中使用xpath,BS4,正则,css选择器等来提取想要的数据时,由于Scrapy是一个重量级框架,每次运行起来都要等待一段时间,因此要去验证我们书写的规则是否正确,是一个比较麻烦的事情,因此Scrapy提供了一个shell,用起来方便测试规则

打开Scrapy Shell

打开cmd终端,进入到Scrapy项目所在目录,进入到Scrapy框架所在的环境中,输入命令:

 scrapy shell url ,就会进入到scrapy的shell环境中,在这个环境中,你可以跟在爬虫的parse方法中一样使用了

例如:

   cd mySpider  进入项目路径

   scrapy shell https://cs.lianjia.com/zufang/  #想要测试的url

   link = response.xpath('//div[@class="content__list--item--main"]//a[@class="twoline"]/@href').extract()

2. 9. 翻页请求的思路

对于要提取如下图中所有页面上的数据该怎么办?

![image.png](attachment:image.png)

回顾requests模块是如何实现翻页请求的:

1. 找到下一页的URL地址

2. 调用requests.get(url)

scrapy实现翻页的思路:

(scrapy并无单独的url这个概念,scrapy中都是需要将url打包成一个请求对象)

1. 找到下一页的url地址

2. 把url地址构造成请求对象,传递给引擎

2.10.如何构造Request对象,并发送请求

2.10.1 实现方法

1. 确定url地址

2. 构造请求,scrapy.Request(url,callback)

   - callback:指定响应体解析的函数名称,表示该请求返回的响应使用哪一个函数进行解析(callback不赋值的话默认是给parse方法解析)

3. 把请求交给引擎:yield scrapy.Request(url,callback)

2.10.2 链家爬虫

通过爬取链家页面信息,学习如何实现翻页请求

 地址:https://xy.lianjia.com/zufang/pg1/

思路分析:

1. 获取首页的响应数据(因为里面有我们想要的翻页链接)

2. 寻找下一页的地址,进行翻页,获取数据

2.10.3 代码实现

在爬虫文件的parse方法中:

        # 开始构造翻页
        # 1,提取下一页url
        all_url = response.xpath('//ul[@style="display:hidden"]//li/a/@href').extract()
        print(all_url)
        for part_url in all_url:
            # 2,判断条件
            if '/zufang/' in part_url:
                next_url = response.urljoin(part_url)
                print("下一页参数信息:", part_url)
                print("下一页链接:", next_url)
                # 构建请求对象 并且返回给引擎
                yield scrapy.Request(url=next_url,callback=self.parse)

 

3.小结

1. scrapy的安装:pip install scrapy

2. 创建scrapy的项目: scrapy startproject myspider

3. 创建scrapy爬虫:在项目目录下执行 scrapy genspider lianjia  lianjia.com

4. 运行scrapy爬虫:在项目目录下执行scrapy crawl 爬虫名字     【scrapy crawl 爬虫名字 --nolog 忽略日志信息】

5. 解析并获取scrapy爬虫中的数据:

   1. response.xpath方法的返回结果是一个类似list的类型,其中包含的是selector对象,操作和列表一样,但是有一些额外的方法

   2. extract() 返回一个包含有字符串的列表

   3. extract_first() 返回列表中的第一个字符串,列表为空没有返回None

6. scrapy管道的基本使用:

   1. 完善pipelines.py中的process_item方法

   2. 在settings.py中设置开启pipeline

7. response响应对象的常用属性

   1. response.url:获取当前响应的url地址

   2. response.request.url:获取当前响应对应的请求的url地址

   3. response.headers:获取响应头

   4. response.urljoin(url) :用于构造绝对url, 当传入的url参数是一个相对地址时, 根据response.url计算出相应的绝对url.

   5. response.body:获取响应体,也就是html代码,byte类型

   6. response.text: 获取响应体,str类型

   7. response.status:获取响应状态码

8. request请求对象的常用属性

   1. request.url(必选):请求页面的url地址,bytes或str类型。

   2. request.callback:页面解析函数,Callback类型,Request请求对象的页面下载完成后,由该参数指定的页面解析函数解析页面,如果未传递该参数,默认调用Spider的parse方法。

   3. request.method:HTTP请求的方法,默认为‘GET’。

   4. request.headers:HTTP请求的头部字典,dict 类型。

   5. request.meta:Request 的元数据字典,dict 类型,用于给框架中其他组件传递信息,比如中间件 Item Pipeline。其他组件可以使用Request 对象的 meta 属性访问该元数据字典 (request.meta), 也用于给响应处理函数传递信息。

   6. request.encoding:url 和 body 参数的编码默认为'utf-8'。如果传入的url或body参数是str 类型,就使用该参数进行编码。

   7. request.dont_filter:默认情况下(dont_filter=False),对同一个url地址多次提交下载请求,后面的请求会被去重过滤器过滤(避免重复下载)。如果将该参数置为True,可以使请求避免被过滤,强制下载。例如:在多次爬取一个内容随时间而变化的页面时(每次使用相同的url),可以将该参数设置为True。

结语:

今天给大家分享的是关于scrapy的初级入门学习,由于这篇的篇幅比较长所有我更新的比较慢,希望大家见谅.这些都是我自己的学习过程中的一些笔记欢迎大家的指正和欢迎大家在评论区和谐讨论。

相关推荐

  1. Scrapycrawlspider爬虫

    2024-05-12 14:18:07       37 阅读
  2. scrapycrawlspider爬虫

    2024-05-12 14:18:07       35 阅读
  3. <span style='color:red;'>Scrapy</span>

    Scrapy

    2024-05-12 14:18:07      12 阅读
  4. 爬虫scrapy管道使用

    2024-05-12 14:18:07       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-12 14:18:07       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-12 14:18:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-12 14:18:07       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-12 14:18:07       20 阅读

热门阅读

  1. 爬虫工具you-get

    2024-05-12 14:18:07       10 阅读
  2. Leetcode 572:另一颗树的子树

    2024-05-12 14:18:07       7 阅读
  3. 【力扣】70.爬楼梯

    2024-05-12 14:18:07       7 阅读
  4. 程序员副业录制课程

    2024-05-12 14:18:07       8 阅读
  5. 指针(3)

    2024-05-12 14:18:07       9 阅读
  6. leetcode 2316.统计无向图中无法互相到达点对数

    2024-05-12 14:18:07       9 阅读
  7. 3.1 Gateway之路由请求和转发

    2024-05-12 14:18:07       10 阅读
  8. 理解并实现区块链智能合约

    2024-05-12 14:18:07       9 阅读
  9. 验证控件的学习

    2024-05-12 14:18:07       6 阅读
  10. 关于Windows驱动中DPC同步的一些见解说明

    2024-05-12 14:18:07       9 阅读
  11. 页面静态化

    2024-05-12 14:18:07       8 阅读