# Scrapy shell
> 譯者:[OSGeo 中國](https://www.osgeo.cn/)
scrappyshell是一個交互式shell,您可以在其中快速調試 scrape 代碼,而不必運行spider。它本來是用來測試數據提取代碼的,但實際上您可以使用它來測試任何類型的代碼,因為它也是一個常規的PythonShell。
shell用于測試xpath或css表達式,并查看它們是如何工作的,以及它們從您試圖抓取的網頁中提取的數據。它允許您在編寫spider時交互地測試表達式,而不必運行spider來測試每個更改。
一旦你熟悉了 Scrapy Shell,你就會發現它是開發和調試 Spider 的寶貴工具。
## 配置shell
如果你有 [IPython](https://ipython.org/) 安裝后,scrapy shell將使用它(而不是標準的python控制臺)。這個 [IPython](https://ipython.org/) 控制臺功能更強大,提供智能自動完成和彩色輸出等功能。
我們強烈建議您安裝 [IPython](https://ipython.org/) ,特別是在使用Unix系統時(其中 [IPython](https://ipython.org/) 擅長)。見 [IPython installation guide](https://ipython.org/install.html) 更多信息。
Scrapy還支持 [bpython](https://www.bpython-interpreter.org/) ,并將嘗試在 [IPython](https://ipython.org/) 不可用。
通過Scrapy的設置,您可以將其配置為使用 `ipython` , `bpython` 或標準 `python` Shell,無論安裝了什么。這是通過設置 `SCRAPY_PYTHON_SHELL` 環境變量;或通過在 [scrapy.cfg](commands.html#topics-config-settings) ::
```py
[settings]
shell = bpython
```
## 啟動Shell
要啟動 Scrapy shell,可以使用 [`shell`](commands.html#std:command-shell) 命令如下:
```py
scrapy shell <url>
```
何處 `<url>` 是要抓取的URL。
[`shell`](commands.html#std:command-shell) 也適用于本地文件。如果你想玩一個網頁的本地副本,這很方便。 [`shell`](commands.html#std:command-shell) 了解本地文件的以下語法::
```py
# UNIX-style
scrapy shell ./path/to/file.html
scrapy shell ../other/path/to/file.html
scrapy shell /absolute/path/to/file.html
# File URI
scrapy shell file:///absolute/path/to/file.html
```
注解
使用相對文件路徑時,請顯式并用 `./` (或) `../` 相關時)。 `scrapy shell index.html` 不會像人們預期的那樣工作(這是設計上的,而不是錯誤)。
因為 [`shell`](commands.html#std:command-shell) 喜歡HTTP URL而不是文件URI,以及 `index.html` 在句法上類似于 `example.com` , [`shell`](commands.html#std:command-shell) 會治療 `index.html` 作為域名并觸發DNS查找錯誤::
```py
$ scrapy shell index.html
[ ... scrapy shell starts ... ]
[ ... traceback ... ]
twisted.internet.error.DNSLookupError: DNS lookup failed:
address 'index.html' not found: [Errno -5] No address associated with hostname.
```
[`shell`](commands.html#std:command-shell) 如果文件調用了 `index.html` 存在于當前目錄中。同樣,要明確。
## 使用Shell
scrappyshell只是一個普通的python控制臺(或者 [IPython](https://ipython.org/) 控制臺,如果你有它的話),它提供一些額外的快捷功能,以方便。
### 可用快捷方式
> * `shelp()` -打印有關可用對象和快捷方式列表的幫助
> * `fetch(url[, redirect=True])` - fetch a new response from the given URL and update all related objects accordingly. You can optionaly ask for HTTP 3xx redirections to not be followed by passing `redirect=False`
> * `fetch(request)` -從給定的請求中獲取新的響應,并相應地更新所有相關對象。
> * `view(response)` -在本地Web瀏覽器中打開給定的響應以進行檢查。這將增加一個 [<base> tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) 到響應主體,以便外部鏈接(如圖像和樣式表)正確顯示。但是請注意,這將在您的計算機中創建一個臨時文件,該文件不會自動刪除。
### 可用的 Scrapy 對象
Scrapy Shell自動從下載的頁面創建一些方便的對象,例如 [`Response`](request-response.html#scrapy.http.Response "scrapy.http.Response") 對象與 [`Selector`](selectors.html#scrapy.selector.Selector "scrapy.selector.Selector") 對象(用于HTML和XML內容)。
這些對象是:
> * `crawler` -電流 [`Crawler`](api.html#scrapy.crawler.Crawler "scrapy.crawler.Crawler") 對象。
> * `spider` -已知用于處理URL的 Spider ,或 [`Spider`](spiders.html#scrapy.spiders.Spider "scrapy.spiders.Spider") 如果沒有為當前URL找到spider,則為。
> * `request` -A [`Request`](request-response.html#scrapy.http.Request "scrapy.http.Request") 上次提取的頁的對象。您可以使用修改此請求 [`replace()`](request-response.html#scrapy.http.Request.replace "scrapy.http.Request.replace") 或者使用 `fetch` 捷徑。
> * `response` -A [`Response`](request-response.html#scrapy.http.Response "scrapy.http.Response") 包含上次提取的頁的對象
> * `settings` - the current [Scrapy settings](settings.html#topics-settings)
## Shell會話示例
下面是一個典型的shell會話的例子,我們從抓取https://scrappy.org頁面開始,然后繼續抓取https://reddit.com頁面。最后,我們修改(reddit)請求方法來發布和重新獲取它,得到一個錯誤。我們通過在Windows中鍵入ctrl-d(在UNIX系統中)或ctrl-z來結束會話。
請記住,在這里提取的數據在您嘗試時可能不相同,因為這些頁面不是靜態的,在您測試時可能已經更改了。這個例子的唯一目的是讓您熟悉下腳料Shell的工作原理。
首先,我們發射炮彈:
```py
scrapy shell 'https://scrapy.org' --nolog
```
然后,shell獲取URL(使用scrapy下載器)并打印可用對象和有用快捷方式的列表(您會注意到這些行都以 `[s]` 前綴):
```py
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x7f07395dd690>
[s] item {}
[s] request <GET https://scrapy.org>
[s] response <200 https://scrapy.org/>
[s] settings <scrapy.settings.Settings object at 0x7f07395dd710>
[s] spider <DefaultSpider 'default' at 0x7f0735891690>
[s] Useful shortcuts:
[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s] fetch(req) Fetch a scrapy.Request and update local objects
[s] shelp() Shell help (print this help)
[s] view(response) View response in a browser
>>>
```
之后,我們可以開始玩對象:
```py
>>> response.xpath('//title/text()').get()
'Scrapy | A Fast and Powerful Scraping and Web Crawling Framework'
>>> fetch("https://reddit.com")
>>> response.xpath('//title/text()').get()
'reddit: the front page of the internet'
>>> request = request.replace(method="POST")
>>> fetch(request)
>>> response.status
404
>>> from pprint import pprint
>>> pprint(response.headers)
{'Accept-Ranges': ['bytes'],
'Cache-Control': ['max-age=0, must-revalidate'],
'Content-Type': ['text/html; charset=UTF-8'],
'Date': ['Thu, 08 Dec 2016 16:21:19 GMT'],
'Server': ['snooserv'],
'Set-Cookie': ['loid=KqNLou0V9SKMX4qb4n; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure',
'loidcreated=2016-12-08T16%3A21%3A19.445Z; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure',
'loid=vi0ZVe4NkxNWdlH7r7; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure',
'loidcreated=2016-12-08T16%3A21%3A19.459Z; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure'],
'Vary': ['accept-encoding'],
'Via': ['1.1 varnish'],
'X-Cache': ['MISS'],
'X-Cache-Hits': ['0'],
'X-Content-Type-Options': ['nosniff'],
'X-Frame-Options': ['SAMEORIGIN'],
'X-Moose': ['majestic'],
'X-Served-By': ['cache-cdg8730-CDG'],
'X-Timer': ['S1481214079.394283,VS0,VE159'],
'X-Ua-Compatible': ['IE=edge'],
'X-Xss-Protection': ['1; mode=block']}
>>>
```
## 從spiders調用shell來檢查響應
有時,您希望檢查在您的 Spider 的某個點上正在處理的響應,如果只是檢查您期望的響應是否到達那里的話。
這可以通過使用 `scrapy.shell.inspect_response` 功能。
下面是一個例子,說明如何從您的 Spider 中命名它:
```py
import scrapy
class MySpider(scrapy.Spider):
name = "myspider"
start_urls = [
"http://example.com",
"http://example.org",
"http://example.net",
]
def parse(self, response):
# We want to inspect one specific response.
if ".org" in response.url:
from scrapy.shell import inspect_response
inspect_response(response, self)
# Rest of parsing code.
```
當你運行 Spider 時,你會得到類似的東西:
```py
2014-01-23 17:48:31-0400 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://example.com> (referer: None)
2014-01-23 17:48:31-0400 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://example.org> (referer: None)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
...
>>> response.url
'http://example.org'
```
然后,您可以檢查提取代碼是否工作:
```py
>>> response.xpath('//h1[@class="fn"]')
[]
```
不,不是這樣的。所以您可以在Web瀏覽器中打開響應,看看它是否是您期望的響應:
```py
>>> view(response)
True
```
最后,單擊ctrl-d(或在Windows中單擊ctrl-z)退出shell并繼續爬網:
```py
>>> ^D
2014-01-23 17:50:03-0400 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://example.net> (referer: None)
...
```
請注意,您不能使用 `fetch` 這里的快捷方式,因為 Scrapy 的引擎被Shell擋住了。然而,當你離開Shell后, Spider 會繼續在它停止的地方爬行,如上圖所示。
- 簡介
- 第一步
- Scrapy at a glance
- 安裝指南
- Scrapy 教程
- 實例
- 基本概念
- 命令行工具
- Spider
- 選擇器
- 項目
- 項目加載器
- Scrapy shell
- 項目管道
- Feed 導出
- 請求和響應
- 鏈接提取器
- 設置
- 例外情況
- 內置服務
- Logging
- 統計數據集合
- 發送電子郵件
- 遠程登錄控制臺
- Web服務
- 解決具體問題
- 常見問題
- 調試spiders
- Spider 合約
- 常用做法
- 通用爬蟲
- 使用瀏覽器的開發人員工具進行抓取
- 調試內存泄漏
- 下載和處理文件和圖像
- 部署 Spider
- AutoThrottle 擴展
- Benchmarking
- 作業:暫停和恢復爬行
- 延伸 Scrapy
- 體系結構概述
- 下載器中間件
- Spider 中間件
- 擴展
- 核心API
- 信號
- 條目導出器
- 其余所有
- 發行說明
- 為 Scrapy 貢獻
- 版本控制和API穩定性