【问题标题】:Scrapy returning a empty json fileScrapy返回一个空的json文件
【发布时间】:2018-02-16 19:43:25
【问题描述】:

我正在尝试从网站获取数据,一切似乎都是正确的,并且 xpath 在 shell 上进行了测试。

# -*- coding: utf-8 -*-

from scrapy.contrib.spiders import CrawlSpider


class KabumspiderSpider(CrawlSpider):
    name = "kabumspider"
    allowed_domain = ["www.kabum.com.br"]
    start_urls = ["https://www.kabum.com.br"]


def parse(self, response):
        categorias = response.xpath('//p[@class = "bot-categoria"]/a/text()').extract()
        links = response.xpath('//p[@class = "bot-categoria"]/a/@href').extract()

        for categoria in zip(categorias, links):

            info = {
                'categoria': categoria[0],
                'link': categoria[1],
            }
            yield info

虽然,输出似乎是:

[

我的代码有什么问题?

【问题讨论】:

  • 你试过在scrapy shell中测试输出吗?此外,您可能应该首先创建项目,将输出写入项目属性并将项目写入 JSON 文件。
  • 我确实使用了 items,但我认为这可能是问题所在,所以我再次使用字典做了一次......在 scrapy shell 中似乎一切正常
  • 如果你把prints 放在for里面,你能看到它们吗?您还启用了任何自定义管道吗?

标签: python json scrapy scrapy-spider scrapy-shell


【解决方案1】:

我运行了刮刀,它对我来说运行良好。我发现的唯一问题是您的 parse 方法在类之外。

# -*- coding: utf-8 -*-

from scrapy.contrib.spiders import CrawlSpider


class KabumspiderSpider(CrawlSpider):
    name = "kabumspider"
    allowed_domain = ["www.kabum.com.br"]
    start_urls = ["https://www.kabum.com.br"]

    def parse(self, response):
        categorias = response.xpath('//p[@class = "bot-categoria"]/a/text()').extract()
        links = response.xpath('//p[@class = "bot-categoria"]/a/@href').extract()

        for categoria in zip(categorias, links):
            info = {
                'categoria': categoria[0],
                'link': categoria[1],
            }
            yield info

【讨论】:

  • 哈哈哈原来是这个错误,犯了这么简单的错误我都不好意思
猜你喜欢
  • 2021-06-22
  • 2016-02-06
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 2015-09-20
  • 1970-01-01
  • 2015-08-13
相关资源
最近更新 更多