Command line tool

版本0.10中的新功能。
Scrapy是通过scrapy命令行工具控制的,在这里称为“ Scrapy工具”,以将其与子命令区分开,我们仅将子命令称为“命令”或“ Scrapy命令”。
Scrapy工具提供了多个命令,用于多种用途,每个命令接受一组不同的参数和选项。
(为了支持独立的scrapyd-deploy,在1.0中已删除scrapy deploy命令。请参阅部署项目。)

配置设置

Scrapy将在标准位置的ini样式scrapy.cfg文件中查找配置参数:

  1. /etc/scrapy.cfgc:\scrapy\scrapy.cfg (系统级),
  2. ~/.config/scrapy.cfg ($XDG_CONFIG_HOME) 以及 ~/.scray.cfg ($HOME) 用来做(用户级)全局设置,
  3. scrapy.cfg 位于Scrapy项目根目录(见下节).

这些文件中的设置将按照列出的优先顺序进行合并:用户定义的值的优先级高于系统级的默认值,并且在定义时,项目级的设置将覆盖所有其他设置。
Scrapy还了解并可以通过许多环境变量进行配置。当前这些是:

Scrapy项目的默认结构

在研究命令行工具及其子命令之前,首先让我们了解Scrapy项目的目录结构。
尽管可以修改,但默认情况下,所有Scrapy项目都具有相同的文件结构,类似于:

scrapy.cfg
myproject/
    __init__.py
    items.py
    middlewares.py
    pipelines.py
    settings.py
    spiders/
        __init__.py
        spider1.py
        spider2.py
        ...

scrapy.cfg文件所在的目录称为项目根目录。该文件包含定义项目设置的python模块的名称。这是一个例子:

[settings]
default = myproject.settings

在项目之间共享根目录

一个项目根目录(包含scrapy.cfg的目录)可以由多个Scrapy项目共享,每个项目都有自己的设置模块。
在这种情况下,必须在scrapy.cfg文件的[settings]下为这些设置模块定义一个或多个别名:

[settings]
default = myproject1.settings
project1 = myproject1.settings
project2 = myproject2.settings

默认情况下,scrapy命令行工具将使用默认设置。使用SCRAPY_PROJECT环境变量来指定其他项目以供scrapy使用:

$ scrapy settings --get BOT_NAME
Project 1 Bot
$ export SCRAPY_PROJECT=project2
$ scrapy settings --get BOT_NAME
Project 2 Bot

使用scrapy工具

您可以先运行不带任何参数的Scrapy工具,它会显示一些用法帮助和可用命令:

Scrapy X.Y - no active project

Usage:
  scrapy <command> [options] [args]

Available commands:
  crawl         Run a spider
  fetch         Fetch a URL using the Scrapy downloader
[...]

如果您在Scrapy项目中,第一行将打印当前活动的项目。在此示例中,它是从项目外部运行的。如果从项目内部运行,它将打印出以下内容:

Scrapy X.Y - project: myproject

Usage:
  scrapy <command> [options] [args]

[...]

创建项目

通常,使用scrapy工具要做的第一件事是创建Scrapy项目:

scrapy startproject myproject [project_dir]

这将在project_dir目录下创建一个Scrapy项目。如果未指定project_dir,则project_dir将与myproject相同。
接下来,进入新项目目录:

cd project_dir

您已经准备好使用scrapy命令管理和控制您的项目。

控制项目

您可以从项目内部使用scrapy工具来控制和管理它们。
例如,创建一个新的蜘蛛:

scrapy genspider mydomain mydomain.com

一些Scrapy命令(例如crawl)必须从Scrapy项目内部运行。请参阅下面的命令参考,以获取有关哪些命令必须在项目内部运行以及哪些不是必须的更多信息。
还请记住,从项目内部运行某些命令时,它们的行为可能略有不同。例如,如果要获取的url与某些特定的爬虫关联,则fetch命令将会覆盖爬虫(例如user_agent属性来覆盖user-agent)。这是有意的,因为fetch命令用于检查爬虫如何下载页面。

可用的工具命令

本节包含可用的内置命令的列表,并带有说明和一些用法示例。请记住,您始终可以通过运行以下命令获取有关每个命令的更多信息:

scrapy <command> -h

您可以使用以下命令查看所有可用命令:

scrapy -h

有两种命令,它们只能在Scrapy项目内部运行(特定于项目的命令),也可以在没有活动的Scrapy项目内部运行(全局命令),尽管它们在项目内部运行时的行为可能略有不同(因为他们会使用项目的覆盖设置)。
全局命令:

  • startproject

  • genspider

  • settings

  • runspider

  • shell

  • fetch

  • view

  • version
    仅项目可用命令:

  • crawl

  • check

  • list

  • edit

  • parse

  • bench

    startproject

  • 语法: scrapy startproject <project_name> [project_dir]

  • 需要项目: 不需要
    project_dir目录下创建一个名为project_name的新Scrapy项目。如果未指定project_dir,则project_dir将与project_name相同。
    用法示例:

    $ scrapy startproject myproject

    genspider

  • 语法: scrapy genspider [-t template] <name> <domain>

  • 需要项目: 不需要
    如果从项目内部调用,则在当前文件夹或当前项目的Spiders文件夹中创建一个新的Spider。<name>参数设置为蜘蛛的名称,而<domain>用于生成允许的域和start_urls蜘蛛的属性。
    用法示例:

    
    $ scrapy genspider -l
    Available templates:
    basic
    crawl
    csvfeed
    xmlfeed

$ scrapy genspider example example.com
Created spider 'example' using template 'basic'

$ scrapy genspider -t crawl scrapyorg scrapy.org
Created spider 'scrapyorg' using template 'crawl'

这只是用于基于预定义模板创建蜘蛛的便利快捷命令,但肯定不是唯一的创建蜘蛛的方法。您可以自己创建蜘蛛源代码文件,而不使用此命令。

###crawl
* 语法: `scrapy crawl <spider>`
* 需要项目: 需要
开始使用蜘蛛抓取。
用法示例:

$ scrapy crawl myspider
[ ... myspider starts crawling ... ]

###check
* 语法: `scrapy check [-l] <spider>
* 需要项目: 需要
运行合法性检查.
用法示例:

$ scrapy check -l
first_spider

  • parse
  • parse_item
    second_spider
  • parse
  • parse_item

$ scrapy check
[FAILED] first_spider:parse_item

'RetailPricex' field is missing

[FAILED] first_spider:parse

Returned 92 requests, expected 0..4

###list
* 语法: `scrapy list`
* 需要项目: 需要
列出当前项目中所有可用的蜘蛛。输出是每行一个蜘蛛。
用法示例:

$ scrapy list
spider1
spider2


###edit
语法: scrapy edit <spider>
* 需要项目: 需要
使用EDITOR环境变量或(如果未设置)EDITOR设置中定义的编辑器来编辑给定的蜘蛛。

在大多数情况下,此命令仅作为便利快捷方式提供,开发人员当然可以选择任何工具或IDE来编写和调试Spider。

用法示例:

$ scrapy edit spider1

fetch

  • 语法: scrapy fetch
  • 需要项目: 不需要
    使用Scrapy下载器下载给定的URL,并将内容写入标准输出。
    关于此命令的有趣之处在于,它会fetch获取蜘蛛如何下载页面的页面。例如,如果蜘蛛具有覆盖用户代理的USER_AGENT属性,它将使用该属性。
    因此,该命令可用于“查看”您的Spider如何获取特定页面。
    如果在项目外部使用,则不会应用任何特定的行为,它只会使用默认的Scrapy下载程序设置。
    支持的选项:
  • --spider=SPIDER: 绕过蜘蛛自动检测并强制使用特定蜘蛛
  • --headers: 打印响应的HTTP标头,而不是响应的正文
  • --no-redirect: 不遵循HTTP 3xx重定向(默认为遵循它们)
    用法示例:
    
    $ scrapy fetch --nolog http://www.example.com/some/page.html
    [ ... html content here ... ]

$ scrapy fetch --nolog --headers http://www.example.com/
{'Accept-Ranges': ['bytes'],
'Age': ['1263 '],
'Connection': ['close '],
'Content-Length': ['596'],
'Content-Type': ['text/html; charset=UTF-8'],
'Date': ['Wed, 18 Aug 2010 23:59:46 GMT'],
'Etag': ['"573c1-254-48c9c87349680"'],
'Last-Modified': ['Fri, 30 Jul 2010 15:30:18 GMT'],
'Server': ['Apache/2.2.3 (CentOS)']}


###view
* 语法: `scrapy view <url>`
* 需要项目: 不需要
在浏览器中打开给定的URL,就像您的Scrapy蜘蛛会“看到”它一样。有时,蜘蛛人看到的页面与普通用户的页面不同,因此可以用来检查蜘蛛“看到”的内容并确认它是您期望的。
Supported options:

--spider=SPIDER: bypass spider autodetection and force use of specific spider
--no-redirect: do not follow HTTP 3xx redirects (default is to follow them)
Usage example:

$ scrapy view http://www.example.com/some/page.html
[ ... browser starts ... ]
shell
Syntax: scrapy shell [url]
Requires project: no
Starts the Scrapy shell for the given URL (if given) or empty if no URL is given. Also supports UNIX-style local file paths, either relative with ./ or ../ prefixes or absolute file paths. See Scrapy shell for more info.

Supported options:

--spider=SPIDER: bypass spider autodetection and force use of specific spider
-c code: evaluate the code in the shell, print the result and exit
--no-redirect: do not follow HTTP 3xx redirects (default is to follow them); this only affects the URL you may pass as argument on the command line; once you are inside the shell, fetch(url) will still follow HTTP redirects by default.
Usage example:

$ scrapy shell http://www.example.com/some/page.html
[ ... scrapy shell starts ... ]

$ scrapy shell --nolog http://www.example.com/ -c '(response.status, response.url)'
(200, 'http://www.example.com/')

# shell follows HTTP redirects by default
$ scrapy shell --nolog http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F -c '(response.status, response.url)'
(200, 'http://example.com/')

# you can disable this with --no-redirect
# (only for the URL passed as command line argument)
$ scrapy shell --no-redirect --nolog http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F -c '(response.status, response.url)'
(302, 'http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F')
parse
Syntax: scrapy parse <url> [options]
Requires project: yes
Fetches the given URL and parses it with the spider that handles it, using the method passed with the --callback option, or parse if not given.

Supported options:

--spider=SPIDER: bypass spider autodetection and force use of specific spider
--a NAME=VALUE: set spider argument (may be repeated)
--callback or -c: spider method to use as callback for parsing the response
--meta or -m: additional request meta that will be passed to the callback request. This must be a valid json string. Example: –meta=’{“foo” : “bar”}’
--cbkwargs: additional keyword arguments that will be passed to the callback. This must be a valid json string. Example: –cbkwargs=’{“foo” : “bar”}’
--pipelines: process items through pipelines
--rules or -r: use CrawlSpider rules to discover the callback (i.e. spider method) to use for parsing the response
--noitems: don’t show scraped items
--nolinks: don’t show extracted links
--nocolour: avoid using pygments to colorize the output
--depth or -d: depth level for which the requests should be followed recursively (default: 1)
--verbose or -v: display information for each depth level
Usage example:

$ scrapy parse http://www.example.com/ -c parse_item
[ ... scrapy log lines crawling example.com spider ... ]

>>> STATUS DEPTH LEVEL 1 <<<
# Scraped Items  ------------------------------------------------------------
[{'name': 'Example item',
 'category': 'Furniture',
 'length': '12 cm'}]

# Requests  -----------------------------------------------------------------
[]
settings
Syntax: scrapy settings [options]
Requires project: no
Get the value of a Scrapy setting.

If used inside a project it’ll show the project setting value, otherwise it’ll show the default Scrapy value for that setting.

Example usage:

$ scrapy settings --get BOT_NAME
scrapybot
$ scrapy settings --get DOWNLOAD_DELAY
0
runspider
Syntax: scrapy runspider <spider_file.py>
Requires project: no
Run a spider self-contained in a Python file, without having to create a project.

Example usage:

$ scrapy runspider myspider.py
[ ... spider starts crawling ... ]
version
Syntax: scrapy version [-v]
Requires project: no
Prints the Scrapy version. If used with -v it also prints Python, Twisted and Platform info, which is useful for bug reports.

bench
New in version 0.17.

Syntax: scrapy bench
Requires project: no
Run a quick benchmark test. Benchmarking.

Custom project commands
You can also add your custom project commands by using the COMMANDS_MODULE setting. See the Scrapy commands in scrapy/commands for examples on how to implement your commands.

COMMANDS_MODULE
Default: '' (empty string)

A module to use for looking up custom Scrapy commands. This is used to add custom commands for your Scrapy project.

Example:

COMMANDS_MODULE = 'mybot.commands'
Register commands via setup.py entry points
Note

This is an experimental feature, use with caution.

You can also add Scrapy commands from an external library by adding a scrapy.commands section in the entry points of the library setup.py file.

The following example adds my_command command:

from setuptools import setup, find_packages

setup(name='scrapy-mymodule',
  entry_points={
    'scrapy.commands': [
      'my_command=my_scrapy_module.commands:MyCommand',
    ],
  },
 )

标签: none 阅读量: 716

添加新评论