【问题标题】:Using TextResponse in Scrapy spider在 Scrapy 蜘蛛中使用 TextResponse
【发布时间】:2021-02-09 01:32:57
【问题描述】:

我有一个处理 XML 页面的基本爬虫:

class MySpider(scrapy.Spider):
    name = "myspider"
    start_urls = [
        "website.com",
    ]
    def parse(self, response):
        for item in response.css("item"):
            yield {...}

我意识到它不能正常工作,因为响应是二进制编码的。我发现了 scrapy TextResponse 对象,它是 Response 的子类,可以处理二进制数据。我不确定如何将它集成到我的刮刀中。我目前的解决方案是覆盖解析函数中的响应对象,如下所示:

class MySpider(scrapy.Spider):
    name = "myspider"
    start_urls = [
        "website.com",
    ]
    def parse(self, response):
        # --- override response object with TextResponse ---
        response = TextResponse(response.url, body=response.body, encoding="utf-8")
        for item in response.css("item"):
            yield {...}

有没有更好的方法让我的蜘蛛使用 TextResponse 而不是基本的 Response 对象?

【问题讨论】:

  • 这对我来说似乎很干净,你到底要找什么?
  • 你为什么没有从 Scrapy 获得TextResponse?如果可以将响应解码为文本,通常会发生这种情况。这可能是 Scrapy 中的一个错误。

标签: python python-3.x scrapy


【解决方案1】:

我通常会做的只是:

def parse(self, response):
    data = response.body.decode('utf-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多