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.pswp.cn/news/390979.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390979.shtml
英文地址,請注明出處:http://en.pswp.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;當您調用它時將…