【问题标题】:Scrapy: why does my response object not have a body_as_unicode method?Scrapy:为什么我的响应对象没有 body_as_unicode 方法?
【发布时间】:2013-01-19 11:35:30
【问题描述】:

我写了一个蜘蛛,第一次运行得很好。我第二次尝试运行它时,它并没有超出start_urls。我尝试fetch scrapy shell 中的 url 并从返回的响应中创建一个 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 中的错误?

【问题讨论】:

    标签: python scrapy


    【解决方案1】:

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

    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 标头?它是否在浏览器中正确呈现?这些问题将有助于了解这是预期行为还是错误。

    【讨论】:

    • 我想通了,这和mongo上的httpcache有关。
    • 我明白了,为什么它第一次起作用是有道理的。可能没有从缓存中正确创建请求。
    • 我在 mongo 中使用github.com/scrapinghub/scmongo 缓存页面,您对确保正确创建请求/响应有任何想法吗?或者我可以强制检索到的对象是 TextResponse(短期解决方案)吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2019-04-01
    相关资源
    最近更新 更多