Scrapy 可以在命令行中用 scrapy
命令来控制
1. Scrapy配置
Scrapy会在 scrapy.cfg
文件中查找配置参数,scrapy也能通过环境变量来配置(如SCRAPY_SETTINGS_MODULE
,SCRAPY_PROJECT
等)。
2. Scrapy项目的目录结构
scrapy.cfg
myproject/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
spider1.py
spider2.py
...
3. 使用scrapy命令
直接在命令行中输入scrapy
命令会出现一些使用方法的介绍,在第一行会显示当前的项目。
新建项目
命令如下:
scrapy startproject myproject
这会创建一个名为myproject
的项目,进入这个目录之后就能用scrapy命令来管理项目了。
管理项目
有些命令必须在一个scrapy项目里面才能执行(例如crawl
命令),而另一些命令则没有限制。
值得注意的是,那些既能在项目外也能在项目内执行的项目在执行时可能会有一些细微的区别。例如在项目内使用scrapy fetch
命令时,如果被fetch的url与某些特定的spider有关联的话,它会覆盖一些参数(如user-agent
)。这是故意的,因为fetch命令就是用来检查spider是如何下载页面的。
4. 可用的命令
scrapy有两类命令,一类是只能在scrapy项目里运行的命令,另一类可以不在一个项目内运行的命令。
Global commands:
startproject
新建项目settings
从Scrapy setting获取指定值runspider
运行spidershell
start the Scrapy shell for the given URL(if given) or empty if no URL is givenfetch
使用Scrapy downloader下载指定的URL页面,并且将内容写到standard output。view
查看spider看到的页面是什么样的version
查看scrpay版本
Project-only commands:
crawl
用一个spider开始爬数据check
run contract checkslist
列出当前project可用的spideredit
使用EDIT
设置中定义的编辑器编辑给定的spiderparse
fetch指定的页面并用指定的spider来处理genspider
新建一个spiderbench
run a quick benchmark test
下面介绍部分命令:
genspider
格式: scrapy genspider [-t template] <name> <domain>
基于指定的模板创建一个spider,这是创建spider的一种便捷的方式,当然也可以在文件中手动创建spider。
从scrapy genspider -l
命令中可以看到这里提供了四种模板:
- basic
- crawl
- csvfeed
- xmlfeed
关于四种template后面会有专门介绍
fetch
The interesting thing about this command is that it fetches the page how the spider would download it. For example, if the spider has a USER_AGENT attribute which overrides the User Agent, it will use that one.
parse
格式:scrapy parse <url> [options]
fetch指定的页面并用指定的spider来处理它,处理函数通过--callback
传递
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--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
5. 自定义命令
你可以通过使用COMMANDS_MODULE
设置的方式来添加自己的额命令。
This is an experimental feature, use with caution.