zoukankan      html  css  js  c++  java
  • 三、Scrapy Shell

    1、简介

      Scrapy终端是一个交互终端,可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看它们的工作方式,方便在爬取的网页中提取数据。

      如果安装了 IPython ,Scrapy终端将使用 IPython (替代标准Python终端)。 IPython 终端与其他相比更为强大,提供智能的自动补全,高亮输出,及其他特性。

      response.url:当前响应的url地址

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

      response.headers:响应头

      response.body:响应体,也就是html代码,默认是byte类型

      response.requests.headers:当前响应的请求头

    2、启动Scrapy Shell

      进入项目的根目录,执行命令来启动shell

      `scrapy shell "url"`

      说明:url为要爬取的网址

      (1)Scrapy Shell根据下载的页面会自动创建一些方便使用的对象,比如`Response`对象,`Selector`对象

      (2)当shell载入后,将得到一个包含response数据的本地response变量,输入`response.body`将输出response的包体,输出`response.headers`可以看到response的包头

      (3)输入`response.selector`时,将获取到一个response初始化的类Selector的对象,此时可以通过使用`response.selector.xpath()或response.selector.css()`来对response进行查询

      (4)Scarpy也提供了一些快捷方式,如`response.xpath()`或`response.css()`同样可以生效。

    3、Selectors选择器

      Scrapy Selectors内置XPath和CSS Selector表达式机制

      Selector有四个基本的方法:

      (1)XPath():传入xpath表达式,返回该表达式所对应的所有节点的selector list列表

      (2)extract():序列化该节点为字符串并返回list

      (3)css():传入CSS表达式,返回该表达式所对应的所有节点的selector list列表,语法同BeautifulSoup4

      (4)re():根据传入的正则表达式对数据进行提取,返回字符串list列表

    4、官方文档

      https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/shell.html

    5、scrapy.shell.inspect_response

      通过scrapy.shell.inspect_response方法来查看spider的某个位置中被处理的response,可以确认期望的response是否到达特定位置。 

      def parse(self, response):
      from scrapy.shell import inspect_response
      inspect_response(response=response,spider=self)
      li_list = response.xpath('//ul[@class="ali"]/li')

       当使用命令执行程序时,程序运行到inspect_response方法时暂停,并切换进shell中,可以方便我们对当前的response进行调试。

      如果调试完成,按ctrl+d来退出终端,恢复爬取。

  • 相关阅读:
    hibernate_0100_HelloWorld
    MYSQL子查询的五种形式
    JSF是什么?它与Struts是什么关系?
    nop指令的作用
    htmlparser实现从网页上抓取数据(收集)
    The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the
    FCKeditor 在JSP上的完全安装
    Java遍历文件夹的2种方法
    充电电池和充电时间说明
    吃知了有什么好处
  • 原文地址:https://www.cnblogs.com/nuochengze/p/12870527.html
Copyright © 2011-2022 走看看