Scrapy:为什么我的响应对象没有body_as_unicode方法?

时间:2013-01-19 11:35:31

标签: python scrapy

我写了一只蜘蛛,它第一次出色地工作。我第二次尝试运行它,它没有超越start_urls。我尝试fetch scrapy shell中的网址,并从返回的响应中创建一个HtmlXPathSelector对象。那是我收到错误的时候

所以步骤是: `

[scrapy shell] fetch('http://example.com') #its something other than example.
[scrapy shell] from scrapy.selector import HtmlXPathSelector
[scrapy shell] hxs = HtmlXPathSelector(response)

---------------------------------------------------------------------------

回溯:

AttributeError                            Traceback (most recent call last)
<ipython-input-3-a486208adf1e> in <module>()
----> 1 HtmlXPathSelector(response)

/home/codefreak/project-r42catalog/env-r42catalog/lib/python2.7/site-packages/scrapy/selector/lxmlsel.pyc in __init__(self, response, text, namespaces, _root, _expr)
     29                 body=unicode_to_str(text, 'utf-8'), encoding='utf-8')
     30         if response is not None:
---> 31             _root = LxmlDocument(response, self._parser)
     32 
     33         self.namespaces = namespaces

/home/codefreak/project-r42catalog/env-r42catalog/lib/python2.7/site-packages/scrapy/selector/lxmldocument.pyc in __new__(cls, response, parser)
     25         if parser not in cache:
     26             obj = object_ref.__new__(cls)
---> 27             cache[parser] = _factory(response, parser)
     28         return cache[parser]
     29 

/home/codefreak/project-r42catalog/env-r42catalog/lib/python2.7/site-packages/scrapy/selector/lxmldocument.pyc in _factory(response, parser_cls)
     11 def _factory(response, parser_cls):
     12     url = response.url
---> 13     body = response.body_as_unicode().strip().encode('utf8') or '<html/>'
     14     parser = parser_cls(recover=True, encoding='utf8')
     15     return etree.fromstring(body, parser=parser, base_url=url)

错误:

AttributeError: 'Response' object has no attribute 'body_as_unicode'

我是否忽略了一些非常明显或偶然发现scrapy中的错误的东西?

1 个答案:

答案 0 :(得分:9)

body_as_unicodeTextResponse的一种方法。如果http响应包含文本内容,则将通过scrapy创建TextResponse或其子类(如HtmlResponse)之一。

In [1]: fetch('http://scrapy.org')
...
In [2]: type(response)
Out[2]: scrapy.http.response.html.HtmlResponse
...
In [3]: fetch('http://www.scrapy.org/site-media/images/logo.png')
...
In [4]: type(response)
Out[4]: scrapy.http.response.Response

在您的情况下,最可能的解释是scrapy认为响应不包含文本。

来自服务器的HTTP响应是否正确设置了Content-Type标头?它是否在浏览器中正确呈现?这些问题有助于了解它是预期的行为还是错误。