Scrapy 笔记(一)
这篇文章主要是对的scrapy命令行使用的一个介绍
创建爬虫项目
scrapy startproject 项目名
例子如下:
scrapy startproject test1 You can start your first spider with: cd test1 scrapy genspider example example.com
这个时候爬虫的目录结构就已经创建完成了,目录结构如下:
|____scrapy.cfg |____test1 | |______init__.py | |____items.py | |____middlewares.py | |____pipelines.py | |____settings.py | |____spiders | | |______init__.py
关于命令详细使用
命令的使用范围
这里的命令分为全局的命令和项目的命令,全局的命令表示可以在任何地方使用,而项目的命令只能在项目目录下使用
全局的命令有:
startproject
genspider
settings
runspider
shell
fetch
view
version
项目命令有:
crawl
check
list
edit
parse
bench
startproject
这个命令没什么过多的用法,就是在创建爬虫项目的时候用
genspider
用于生成爬虫,这里scrapy提供给我们不同的几种模板生成spider,默认用的是basic,我们可以通过命令查看所有的模板
localhost:test1 zhaofan$ scrapy genspider -l Available templates: basic crawl csvfeed xmlfeed localhost:test1 zhaofan$
当我们创建的时候可以指定模板,不指定默认用的basic,如果想要指定模板则通过
scrapy genspider -t 模板名字
localhost:test1 zhaofan$ scrapy genspider -t crawl zhihuspider zhihu.com Created spider 'zhihuspider' using template 'crawl' in module: test1.spiders.zhihuspider localhost:test1 zhaofan$
crawl
这个是用去启动spider爬虫格式为:
scrapy crawl 爬虫名字
这里需要注意这里的爬虫名字和通过scrapy genspider 生成爬虫的名字是一致的
check
用于检查代码是否有错误,scrapy check
list
scrapy list列出所有可用的爬虫
fetch
scrapy fetch url地址
该命令会通过scrapy downloader 讲网页的源代码下载下来并显示出来
这里有一些参数:
--nolog 不打印日志
--headers 打印响应头信息
--no-redirect 不做跳转
view
scrapy view url地址
该命令会讲网页document内容下载下来,并且在浏览器显示出来
settings
获取当前的配置信息
通过scrapy settings -h可以获取这个命令的所有帮助信息
localhost:jobboleSpider zhaofan$ scrapy settings -h Usage ===== scrapy settings [options] Get settings values Options ======= --help, -h show this help message and exit --get=SETTING print raw setting value --getbool=SETTING print setting value, interpreted as a boolean --getint=SETTING print setting value, interpreted as an integer --getfloat=SETTING print setting value, interpreted as a float --getlist=SETTING print setting value, interpreted as a list Global Options -------------- --logfile=FILE log file. if omitted stderr will be used --loglevel=LEVEL, -L LEVEL log level (default: DEBUG) --nolog disable logging completely --profile=FILE write python cProfile stats to FILE --pidfile=FILE write process ID to FILE --set=NAME=VALUE, -s NAME=VALUE set/override setting (may be repeated) --pdb enable pdb on failure
拿一个例子进行简单的演示:(这里是我的这个项目的settings配置文件中配置了数据库的相关信息,可以通过这种方式获取,如果没有获取的则为None)
localhost:jobboleSpider zhaofan$ scrapy settings --get=MYSQL_HOST 192.168.1.18 localhost:jobboleSpider zhaofan$
runspider
这个和通过crawl启动爬虫不同,这里是scrapy runspider 爬虫文件名称
所有的爬虫文件都是在项目目录下的spiders文件夹中
version
查看版本信息,并查看依赖库的信息
localhost:~ zhaofan$ scrapy version Scrapy 1.3.2 localhost:~ zhaofan$ scrapy version -v Scrapy : 1.3.2 lxml : 3.7.3.0 libxml2 : 2.9.4 cssselect : 1.0.1 parsel : 1.1.0 w3lib : 1.17.0 Twisted : 17.1.0 Python : 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) - [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] pyOpenSSL : 16.2.0 (OpenSSL 1.0.2k 26 Jan 2017) Platform : Darwin-16.6.0-x86_64-i386-64bit