在Scrapy中获取http.response对象的最简单方法

时间:2016-06-13 20:31:21

标签: python scrapy

我是Scrapy的新手,我正在尝试获取网页的内容"到一个响应对象(如果我正确理解)。

我关注http://doc.scrapy.org/en/latest/topics/selectors.html, 然而,它在scrapy shell中有效。我想直接在python代码中使用它。

我编写代码来废弃http://doc.scrapy.org/en/latest/_static/selectors-sample1.html

import scrapy
from scrapy.http import HtmlResponse
URL = 'http://doc.scrapy.org/en/latest/_static/selectors-sample1.html'
response = HtmlResponse(url=URL)    
print response.selector.xpath('//title/text()')

,输出

>> []

为什么我无法获得正确的头衔价值?似乎HtmlResponse()没有从网上下载数据......为什么?我该怎么办?

非常感谢你!

1 个答案:

答案 0 :(得分:5)

您的陈述

response = HtmlResponse(url=URL)

仅构建a "local scope" HtmlResponse object,空体。它不会下载任何内容,特别是http://doc.scrapy.org/en/latest/_static/selectors-sample1.html的资源。

在Scrapy中,您通常不会自己构建HtmlResponse个对象,当Scrapy框架完成处理您提供的Request实例时,让Scrapy框架为您构建它们,例如: Request(url='http://doc.scrapy.org/en/latest/_static/selectors-sample1.html')

如果您正在尝试使用Scrapy,我建议您使用scrapy shell:在交互式shell中,您可以触发下载(并获取"真实" Response对象以便与之配合使用)使用fetch('http://someurl')

$ scrapy shell
2016-06-14 10:59:31 [scrapy] INFO: Scrapy 1.1.0 started (bot: scrapybot)
(...)
[s] Available Scrapy objects:
[s]   crawler    <scrapy.crawler.Crawler object at 0x7f1a6591d588>
[s]   item       {}
[s]   settings   <scrapy.settings.Settings object at 0x7f1a6ce290f0>
[s] Useful shortcuts:
[s]   shelp()           Shell help (print this help)
[s]   fetch(req_or_url) Fetch request (or URL) and update local objects
[s]   view(response)    View response in a browser
>>> fetch('http://doc.scrapy.org/en/latest/_static/selectors-sample1.html')
2016-06-14 10:59:51 [scrapy] INFO: Spider opened
2016-06-14 10:59:51 [scrapy] DEBUG: Crawled (200) <GET http://doc.scrapy.org/en/latest/_static/selectors-sample1.html> (referer: None)
>>> response.xpath('//title/text()').extract()
['Example website']

在shell之外,要实际下载数据,您需要:

  • 子类scrapy.Spider
  • 定义从哪里开始下载的网址,
  • 并编写回调方法来处理下载的数据,包含在传递给它们的Response个对象中

一个非常简单的例子(在一个名为test.py的文件中:

import scrapy


class TestSpider(scrapy.Spider):

    name = 'testspider'

    # start_urls is special and internally it builds Request objects for each of the URLs listed
    start_urls = ['http://doc.scrapy.org/en/latest/_static/selectors-sample1.html']

    def parse(self, response):
        yield {
            'title': response.xpath('//h1/text()').extract_first()
        }

然后你需要运行蜘蛛。 Scrapy有一个运行单文件蜘蛛的命令:

$ scrapy runspider test.py 

你在控制台中得到了这个:

2016-06-14 10:48:05 [scrapy] INFO: Scrapy 1.1.0 started (bot: scrapybot)
2016-06-14 10:48:05 [scrapy] INFO: Overridden settings: {}
2016-06-14 10:48:06 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats', 'scrapy.extensions.corestats.CoreStats']
2016-06-14 10:48:06 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-06-14 10:48:06 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-06-14 10:48:06 [scrapy] INFO: Enabled item pipelines:
[]
2016-06-14 10:48:06 [scrapy] INFO: Spider opened
2016-06-14 10:48:06 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-06-14 10:48:06 [scrapy] DEBUG: Crawled (200) <GET http://doc.scrapy.org/en/latest/_static/selectors-sample1.html> (referer: None)
2016-06-14 10:48:06 [scrapy] DEBUG: Scraped from <200 http://doc.scrapy.org/en/latest/_static/selectors-sample1.html>
{'title': 'Example website'}
2016-06-14 10:48:06 [scrapy] INFO: Closing spider (finished)
2016-06-14 10:48:06 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 252,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 501,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2016, 6, 14, 8, 48, 6, 564591),
 'item_scraped_count': 1,
 'log_count/DEBUG': 2,
 'log_count/INFO': 7,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2016, 6, 14, 8, 48, 6, 85693)}
2016-06-14 10:48:06 [scrapy] INFO: Spider closed (finished)

如果您真的想要使用选择器,而不是实际下载任何网络数据,假设您已经在本地拥有数据(例如在浏览器中从view-source:进行复制),您可以这样做,但您需要提供身体:

>>> response = HtmlResponse(url=URL, body='''
... <!DOCTYPE html>
... <html>
...   <head>
...   </head>
...   <body>
...       <h1>Herman Melville - Moby-Dick</h1>
... 
...       <div>
...         <p>
...           Availing himself of the mild, summer-cool weather that now reigned in these latitudes, ... them a care-killing competency.
...         </p>
...       </div>
...   </body>
... </html>''', encoding='utf8')
>>> response.xpath('//h1')
[<Selector xpath='//h1' data='<h1>Herman Melville - Moby-Dick</h1>'>]
>>> response.xpath('//h1').extract()
['<h1>Herman Melville - Moby-Dick</h1>']
>>>