scrapy常用工具备忘

scrapy常用的命令分为全局和项目两种命令,全局命令就是不需要依靠scrapy项目,可以在全局环境下运行,而项目命令需要在scrapy项目里才能运行。
一、全局命令
##使用scrapy -h可以看到常用的全局命令

[root@aliyun ~]# scrapy -h
Scrapy 1.5.0 - no active projectUsage:scrapy <command> [options] [args]Available commands:bench         Run quick benchmark testfetch         Fetch a URL using the Scrapy downloadergenspider     Generate new spider using pre-defined templatesrunspider     Run a self-contained spider (without creating a project)settings      Get settings valuesshell         Interactive scraping consolestartproject  Create new projectversion       Print Scrapy versionview          Open URL in browser, as seen by Scrapy

在bench下面的都是全局命令,bench是特殊的,即使在Available 下面展示,但仍然属于项目命令。
1、fetch命令
##fetch主要用来显示爬虫爬取的过程。
scrapy fetch 网址

[root@aliyun ~]# scrapy fetch http://www.baidu.com
2018-03-15 10:50:02 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: scrapybot)
2018-03-15 10:50:02 [scrapy.utils.log] INFO: Versions: lxml 4.1.1.0, libxml2 2.9.1, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.4.2 (default, Mar 15 2018, 10:26:10) - [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)], pyOpenSSL 17.5.0 (OpenSSL 1.0.2k-fips  26 Jan 2017), cryptography 2.1.4, Platform Linux-3.10.0-514.26.2.el7.x86_64-x86_64-with-centos-7.4.1708-Core
2018-03-15 10:50:02 [scrapy.crawler] INFO: Overridden settings: {}
2018-03-15 10:50:02 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.memusage.MemoryUsage','scrapy.extensions.telnet.TelnetConsole','scrapy.extensions.corestats.CoreStats','scrapy.extensions.logstats.LogStats']
2018-03-15 10:50:02 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware','scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware','scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware','scrapy.downloadermiddlewares.useragent.UserAgentMiddleware','scrapy.downloadermiddlewares.retry.RetryMiddleware','scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware','scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware','scrapy.downloadermiddlewares.redirect.RedirectMiddleware','scrapy.downloadermiddlewares.cookies.CookiesMiddleware','scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware','scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-03-15 10:50:02 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware','scrapy.spidermiddlewares.offsite.OffsiteMiddleware','scrapy.spidermiddlewares.referer.RefererMiddleware','scrapy.spidermiddlewares.urllength.UrlLengthMiddleware','scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-03-15 10:50:02 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-03-15 10:50:02 [scrapy.core.engine] INFO: Spider opened
2018-03-15 10:50:02 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-03-15 10:50:02 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-03-15 10:50:02 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.baidu.com> (referer: None)
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a>  <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号  <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>2018-03-15 10:50:02 [scrapy.core.engine] INFO: Closing spider (finished)
2018-03-15 10:50:02 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 212,'downloader/request_count': 1,'downloader/request_method_count/GET': 1,'downloader/response_bytes': 1476,'downloader/response_count': 1,'downloader/response_status_count/200': 1,'finish_reason': 'finished','finish_time': datetime.datetime(2018, 3, 15, 2, 50, 2, 425038),'log_count/DEBUG': 2,'log_count/INFO': 7,'memusage/max': 44892160,'memusage/startup': 44892160,'response_received_count': 1,'scheduler/dequeued': 1,'scheduler/dequeued/memory': 1,'scheduler/enqueued': 1,'scheduler/enqueued/memory': 1,'start_time': datetime.datetime(2018, 3, 15, 2, 50, 2, 241466)}
2018-03-15 10:50:02 [scrapy.core.engine] INFO: Spider closed (finished)

##执行这条命令时我出现了一个错误
ImportError: No module named _sqlite3
##解决的办法是yum安装sqlite-devel,然后重新编译安装python

yum install -y sqlite-devel
cd /usr/local/src/Python-3.4.2
./configure prefix=/usr/local/python3
make && make install
ln -fs /usr/local/python3/bin/python3 /usr/bin/python

##注意,如果在scrapy项目目录之外执行这条命令,会使用scrapy默认的爬虫来进行爬取,如果在scrapy项目目录内运行命令,则会调用该项目的爬虫来进行网页的爬取。
##可以通过scrapy fetch -h 来查看命令参数

[root@aliyun ~]# scrapy fetch -h
Usage
=====scrapy fetch [options] <url>Fetch a URL using the Scrapy downloader and print its content to stdout. You
may want to use --nolog to disable loggingOptions
=======
--help, -h              show this help message and exit
--spider=SPIDER         use this spider
--headers               print response HTTP headers instead of body
--no-redirect           do not handle HTTP 3xx status codes and print responseas-isGlobal Options
--------------
--logfile=FILE          log file. if omitted stderr will be used
--loglevel=LEVEL, -L LEVELlog 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=VALUEset/override setting (may be repeated)
--pdb                   enable pdb on failure

通过headers可以获取网页的头部信息,通过logfile可以指定日志文件的存储,nolog可以控制不显示运行爬取的日志,spider可以控制用哪个爬虫,loglevel控制日志的等级。
##通过headers来获取网页的头部信息,nolog参数不显示爬取过程的日志。

[root@aliyun ~]# scrapy fetch --headers --nolog http://www.baidu.com
> User-Agent: Scrapy/1.5.0 (+https://scrapy.org)
> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
> Accept-Language: en
> Accept-Encoding: gzip,deflate
>
< Content-Type: text/html
< Last-Modified: Mon, 23 Jan 2017 13:28:28 GMT
< Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
< Server: bfe/1.0.8.18
< Date: Thu, 15 Mar 2018 03:15:23 GMT
< Pragma: no-cache
< Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/

通过使用fetch可以很方便显示出爬取网页的过程。
2、runspider命令
scrapy使用runspider命令,可以实现不用scrapy项目直接运行一个爬虫文件。

3、setting命令
setting可以查看scrapy对应的配置信息,如果在scrapy项目目录内使用就是查看项目的配置信息,如果在全局使用,那么就是查看默认配置信息。
##可以通过--get BOT_NAME来查看对应的scrapy信息,通过再项目目录执行以及在全局运行。

[root@aliyun test_scrapy]# cd /python/test_scrapy/myfirstpjt/
[root@aliyun myfirstpjt]# scrapy settings --get BOT_NAME
myfirstpjt
[root@aliyun myfirstpjt]# cd
[root@aliyun ~]# scrapy settings --get BOT_NAME
scrapybot

4、shell命令
shell可以启动scrapy的交互终端(scrapy shell),常常在开发以及测试时候使用。
##在全局下执行

5、startproject命令
用于创建scrapy项目。scrapy startproject projectname
6、version命令
version命令可以显示scrapy的版本

[root@aliyun ~]# scrapy version
Scrapy 1.5.0
##其他相关版本信息
[root@aliyun ~]# scrapy version -v
Scrapy       : 1.5.0
lxml         : 4.1.1.0
libxml2      : 2.9.1
cssselect    : 1.0.3
parsel       : 1.4.0
w3lib        : 1.19.0
Twisted      : 17.9.0
Python       : 3.4.2 (default, Mar 15 2018, 10:26:10) - [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
pyOpenSSL    : 17.5.0 (OpenSSL 1.0.2k-fips  26 Jan 2017)
cryptography : 2.1.4
Platform     : Linux-3.10.0-514.26.2.el7.x86_64-x86_64-with-centos-7.4.1708-Core

7、view命令
view可以下载网页,并且直接用浏览器查看
scrapy view url

二、项目命令
##项目命令要在项目的目录下运行
1、bench命令
bench能测试本地硬件的性能

[root@aliyun myfirstpjt]# scrapy bench
……
2018-03-16 14:56:22 [scrapy.extensions.logstats] INFO: Crawled 255 pages (at 1500 pages/min), scraped 0 items (at 0 items/min)
2018-03-16 14:56:23 [scrapy.extensions.logstats] INFO: Crawled 279 pages (at 1440 pages/min), scraped 0 items (at 0 items/min)
2018-03-16 14:56:24 [scrapy.extensions.logstats] INFO: Crawled 303 pages (at 1440 pages/min), scraped 0 items (at 0 items/min)
……
##从返回中看到每分钟大概能爬取1440个页面

2、genspider命令
genspider可以用来创建scrapy爬虫文件,这是一种快速创建爬虫文件的方式。
##查看当前可以使用的爬虫模板

[root@aliyun myfirstpjt]# scrapy genspider -l
Available templates:basiccrawlcsvfeedxmlfeed

##基于其中一个模板创建一个爬虫文件,scrapy genspider -t 模板 新爬虫名 新爬虫爬取的域名

[root@aliyun myfirstpjt]# scrapy genspider -t basic test www.baidu.com
Created spider 'test' using template 'basic' in module:myfirstpjt.spiders.test

##在项目目录内,能看到创建的test.py文件,里面已经写好了域名。

[root@aliyun myfirstpjt]# cd myfirstpjt/
[root@aliyun myfirstpjt]# ls
__init__.py  items.py  middlewares.py  pipelines.py  __pycache__  settings.py  spiders
[root@aliyun myfirstpjt]# cd spiders/
[root@aliyun spiders]# ls
__init__.py  __pycache__  test.py
[root@aliyun spiders]# cat test.py 
# -*- coding: utf-8 -*-
import scrapyclass TestSpider(scrapy.Spider):name = 'test'allowed_domains = ['www.baidu.com']start_urls = ['http://www.baidu.com/']def parse(self, response):pass

3、check命令
check命令可以对爬虫文件进行一种交互式的检查。
scrapy check 爬虫名

##检查爬虫文件检查通过
[root@aliyun myfirstpjt]# scrapy check test----------------------------------------------------------------------
Ran 0 contracts in 0.000sOK

4、crawl命令
crawl命令可以启动某个爬虫。
scrapy crawl 爬虫名

[root@aliyun myfirstpjt]# scrapy crawl test --loglevel=INFO
2018-03-16 18:35:39 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: myfirstpjt)
2018-03-16 18:35:39 [scrapy.utils.log] INFO: Versions: lxml 4.1.1.0, libxml2 2.9.1, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.4.2 (default, Mar 15 2018, 10:26:10) - [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)], pyOpenSSL 17.5.0 (OpenSSL 1.0.2k-fips  26 Jan 2017), cryptography 2.1.4, Platform Linux-3.10.0-514.26.2.el7.x86_64-x86_64-with-centos-7.4.1708-Core
2018-03-16 18:35:39 [scrapy.crawler] INFO: Overridden settings: {'ROBOTSTXT_OBEY': True, 'LOG_LEVEL': 'INFO', 'SPIDER_MODULES': ['myfirstpjt.spiders'], 'BOT_NAME': 'myfirstpjt', 'NEWSPIDER_MODULE': 'myfirstpjt.spiders'}
……'start_time': datetime.datetime(2018, 3, 16, 10, 35, 39, 671815)}
2018-03-16 18:35:39 [scrapy.core.engine] INFO: Spider closed (finished)

5、list命令
list命令可以列出当前使用的爬虫文件。

[root@aliyun myfirstpjt]# scrapy list
test

6、edit命令
edit命令可以直接编辑某个爬虫文件,在linux中使用比较好。

[root@aliyun myfirstpjt]# scrapy edit test

7、parse命令
parse命令可以实现获取指定的URL网址,并使用对应的爬虫文件进行处理和分析。

[root@aliyun myfirstpjt]# scrapy parse http://www.baidu.com --nolog>>> STATUS DEPTH LEVEL 0 <<<
# Scraped Items  ------------------------------------------------------------
[]
# Requests  -----------------------------------------------------------------
[]

转载于:https://blog.51cto.com/lsfandlinux/2087747

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390979.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

机器学习模型 非线性模型_机器学习:通过预测菲亚特500的价格来观察线性模型的工作原理...

机器学习模型 非线性模型Introduction介绍 In this article, I’d like to speak about linear models by introducing you to a real project that I made. The project that you can find in my Github consists of predicting the prices of fiat 500.在本文中&#xff0c;…

NOIP赛前模拟20171027总结

题目&#xff1a; 1.寿司 给定一个环形的RB串要求经过两两互换后RB分别形成两段连续区域,求最少操作次数(算法时间O(n)) 2.金字塔 给定一个金字塔的侧面图有n层已知每一层的宽度高度均为1要求在图中取出恰好K个互不相交的矩形&#xff08;边缘可以重叠&#xff09;,求最多可以取…

虚幻引擎 js开发游戏_通过编码3游戏学习虚幻引擎4-5小时免费游戏开发视频课程

虚幻引擎 js开发游戏One of the most widely used game engines is Unreal Engine by Epic Games. On the freeCodeCamp.org YouTube channel, weve published a comprehensive course on how to use Unreal Engine with C to develop games.Epic Games的虚幻引擎是使用最广泛的…

建造者模式什么时候使用?

问题&#xff1a;建造者模式什么时候使用&#xff1f; 建造者模式在现实世界里面的使用例子是什么&#xff1f;它有啥用呢&#xff1f;为啥不直接用工厂模式 回答一 下面是使用这个模式的一些理由和Java的样例代码&#xff0c;但是它是由设计模式的4个人讨论出来的建造者模式…

TP5_学习

2017.10.27&#xff1a;1.index入口跑到public下面去了 2.不能使用 define(BIND_MODULE,Admin);自动生成模块了&#xff0c;网上查了下&#xff1a; \think\Build::module(Admin);//亲测,可用 2017.10.28:1.一直不知道怎么做查询显示和全部显示&#xff0c;原来如此简单&#x…

sql sum语句_SQL Sum语句示例说明

sql sum语句SQL中的Sum语句是什么&#xff1f; (What is the Sum statement in SQL?) This is one of the aggregate functions (as is count, average, max, min, etc.). They are used in a GROUP BY clause as it aggregates data presented by the SELECT FROM WHERE port…

10款中小企业必备的开源免费安全工具

10款中小企业必备的开源免费安全工具 secist2017-05-188共527453人围观 &#xff0c;发现 7 个不明物体企业安全工具很多企业特别是一些中小型企业在日常生产中&#xff0c;时常会因为时间、预算、人员配比等问题&#xff0c;而大大减少或降低在安全方面的投入。这时候&#xf…

为什么Java里面没有 SortedList

问题&#xff1a;为什么Java里面没有 SortedList Java 里面有SortedSet和SortedMap接口&#xff0c;它们都属于Java的集合框架和提供对元素进行排序的方法 然鹅&#xff0c;在我的认知里Java就没有SortedList这个东西。你只能使用java.util.Collections.sort()去排序一个list…

图片主成分分析后的可视化_主成分分析-可视化

图片主成分分析后的可视化If you have ever taken an online course on Machine Learning, you must have come across Principal Component Analysis for dimensionality reduction, or in simple terms, for compression of data. Guess what, I had taken such courses too …

回溯算法和递归算法_回溯算法:递归和搜索示例说明

回溯算法和递归算法Examples where backtracking can be used to solve puzzles or problems include:回溯可用于解决难题或问题的示例包括&#xff1a; Puzzles such as eight queens puzzle, crosswords, verbal arithmetic, Sudoku [nb 1], and Peg Solitaire. 诸如八个皇后…

C#中的equals()和==

using System;namespace EqualsTest {class EqualsTest{static void Main(string[] args){//值类型int x 1;int y 1;Console.WriteLine(x y);//TrueConsole.WriteLine(x.Equals(y));//True //引用类型A a new A();B b new B();//Console.WriteLine(ab);//报错…

JPA JoinColumn vs mappedBy

问题&#xff1a;JPA JoinColumn vs mappedBy 两者的区别是什么呢 Entity public class Company {OneToMany(cascade CascadeType.ALL , fetch FetchType.LAZY)JoinColumn(name "companyIdRef", referencedColumnName "companyId")private List<B…

TP引用样式表和js文件及验证码

TP引用样式表和js文件及验证码 引入样式表和js文件 <script src"__PUBLIC__/bootstrap/js/jquery-1.11.2.min.js"></script> <script src"__PUBLIC__/bootstrap/js/bootstrap.min.js"></script> <link href"__PUBLIC__/bo…

pytorch深度学习_深度学习和PyTorch的推荐系统实施

pytorch深度学习The recommendation is a simple algorithm that works on the principle of data filtering. The algorithm finds a pattern between two users and recommends or provides additional relevant information to a user in choosing a product or services.该…

什么是JavaScript中的回调函数?

This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.本文简要介绍了JavaScript编程语言中的回调函数的概念和用法。 函数就是对象 (Functions are Objects) The first thing we need to know i…

Java 集合-集合介绍

2017-10-30 00:01:09 一、Java集合的类关系图 二、集合类的概述 集合类出现的原因&#xff1a;面向对象语言对事物的体现都是以对象的形式&#xff0c;所以为了方便对多个对象的操作&#xff0c;Java就提供了集合类。数组和集合类同是容器&#xff0c;有什么不同&#xff1a;数…

为什么Java不允许super.super.method();

问题&#xff1a;为什么Java不允许super.super.method(); 我想出了这个问题&#xff0c;认为这个是很好解决的&#xff08;也不是没有它就不行的&#xff09;如果可以像下面那样写的话&#xff1a; Override public String toString() {return super.super.toString(); }我不…

Exchange 2016部署实施案例篇-04.Ex基础配置篇(下)

上二篇我们对全新部署完成的Exchange Server做了基础的一些配置&#xff0c;今天继续基础配置这个话题。 DAG配置 先决条件 首先在配置DGA之前我们需要确保DAG成员服务器上磁盘的盘符都是一样的&#xff0c;大小建议最好也相同。 其次我们需要确保有一块网卡用于数据复制使用&…

数据库课程设计结论_结论:

数据库课程设计结论In this article, we will learn about different types[Z Test and t Test] of commonly used Hypothesis Testing.在本文中&#xff0c;我们将学习常用假设检验的不同类型[ Z检验和t检验 ]。 假设是什么&#xff1f; (What is Hypothesis?) This is a St…

JavaScript数据类型:Typeof解释

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well.typeof是一个JavaScript关键字&#xff0c;当您调用它时将…