Scrapy:Scrapy shell

Scrapy shell

scrapy shell是一个你可以快速尝试和调试抓取代码的互动窗口,而不用运行爬虫。这对测试数据提取代码很有用,但是实际上作为一个python shell 它可以测试任何种类的代码。

shell用来测试Xpath or css 表达式,来看他们是如何工作你会从要抓取的页面中提取什么数据。它可以在你写爬虫时互动的测试你的表达式,而不用运行爬虫来测试所有改变,

一旦你熟悉了这个shell,你会发现这是一个超好用的工具用来发展和调试你的爬虫。

Configuring the shell

如果你下载了IPython,scrapy shell 会使用这个(而不是标准python控制台)。IPython控制台更加强大并提供自动补全,带色彩输出和其他东西。

See the IPython installation guide for more info.# 建议你下载IPython,特别是你在Unix 系统下工作。

也支持bpython ,在ipython不能用时会使用。

通过scrapy设置你可以配置它使用ipython bpython 或者标准python窗口,而不管那个下载了。这通过SCRAPY_PYTHON_SHELL 环境变量来设置,或者在你的scrapy.cfg文件中定义。

[settings]
shell = bpython

Launch the shell

使用shell 命令运行scrapy shell

scrapy shell <url>

<url> 就是你想爬的

shell 可以使用本地路径。如果你想使用本地复制的网络页面也是很简单的,shell 理解下面的语法:

# 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

Note

当你使用相对文件路径时,要明确并前置的使用./(or …/ 当相关时)。scrapy shell index.html 将按照预期的不会工作(这是设计不是bug)

因为shell比起文件urls 更喜欢 http urls,并且index.html 在语法上跟example.com 一样。shell 将对待index.html作为一个域名并且触发DNS查找错误。

$ 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.

要明确,如果当前目录中存在一个叫index.html的文件,shell不会预先测试。

Using the shell

scrapy shell 就是一个通常的python控制台(或ipython的)提供一些额外的函数简写为了方便。

Available Shortcuts

  • shelp() - 打印帮助列表,那些可使用的对象和简写。
  • fetch(url[, redirect=True]) - 从所给的url 中获取新的response, 相应的并更新所有相关的对象。你可以通过传递 redirect=False 来禁止重定向。
  • fetch(request) - 从所给的请求中获取响应,并相应的更换所有相关的对象。
  • view(response) - 用你的浏览器打开所给的响应,为了检查。这将增加一个标签在响应体中,为了外部连接(像图像和格式表)来正确展示。注意,这会创建一个临时的文件在电脑中,将不会自动移除。

Available Scrapy objects

scrapy shell 自动的创建一些方便的对象从下载的页面中,像response 对象和selector 对象(对html and xml内容)

Those objects are:

  • crawler - the current Crawler object.
  • spider - 就是用来处理url的爬虫,如果没人spider 发现当前的url,那就是一个spider 对象。。。
  • request - 最后获取页面的request对象,你你可以使用replace()来修改请求,或获取一个新的请求(不用离开shell)使用fetch 简写。
  • response - 包含了最后获取页面的 Response 对象。
  • settings - t当前scrapy 的设置。

Example of shell session

这是一个典型shell会话的列子,从xxx网站开始抓取,然后继续抓取xxx。最终,我们修改请求方法成POST 并重新获取他来得到错误。结束会话通过使用ctrl+z(window) ctrl+d (Unix)

注意当你尝试的时候提取出来的数据可能不一样,因为这些页面不是静态的,会改变。这只是让你熟悉scrapy shell 怎样工作的。

First, we launch the shell:

scrapy shell 'https://scrapy.org' --nolog

Note

从命令行中运行scrapy shell时将urls 闭合在引号内,否则包含参数(即&字符)的url不会工作。

On Windows, use double quotes instead:

scrapy shell "https://scrapy.org" --nolog

然后shell获取url(使用scrapy 下载器)并且打印可使用对象和简写的列表(你可以看到这些行以[s]前缀开始。)

[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

>>>

After that, we can start playing with the objects:

>>> response.xpath('//title/text()').get()
'Scrapy | A Fast and Powerful Scraping and Web Crawling Framework'
>>> fetch("https://old.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']}

Invoking the shell from spiders to inspect responses

有时你想检查爬虫在某个点上正在处理响应

可以使用scrapy.shell.inspect_response 函数。

Here’s an example of how you would call it from your spider:

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)          # 就是在爬虫中调用shell 来检查响应吧。

        # Rest of parsing code.

When you run the spider, you will get something similar to this:

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'

然后你可以检查提取代码是否在工作。

>>> response.xpath('//h1[@class="fn"]')
[]

然而没有,所有你可以在浏览器中打开响应,查看是否时你期望的响应

>>> view(response)
True

最后使用ctrl+z来离开设立了并恢复爬取。

>>> ^D
2014-01-23 17:50:03-0400 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://example.net> (referer: None)
...

注意,因为scrapy引擎被shell阻止,所以你不能使用fetch简写了,但是你离开shell后,爬虫会继续在停止的地方爬行,如上所示。

猜你喜欢

转载自blog.csdn.net/weixin_46192930/article/details/106756000