【问题标题】:Scrapy - how to prevent output lines with blank element?Scrapy - 如何防止带有空白元素的输出行?
【发布时间】:2013-10-20 22:12:16
【问题描述】:

使用一个非常基本的 Scrapy 脚本,我想确保我的输出行都不包含空白项。

也就是说,说我有标准

    items = []
    for list in lists:
        item = TypeItem()
        item['thing1'] = list.select('h1/text()').extract()
        item['thing2'] = list.select('h2/text()').extract()
        item['thing3'] = list.select('h3/text()').extract()
        items.append(item)
    return(items)

我想阻止任何 csv 行显示“thing1,,thing3”或“,thing2”等。

(我是stackoverflow的新手,所以我不知道一次问多个问题是否合适,但由于它们是相关的,如果可以的话:

Q2:如果我在 items.append(item) 之前勾选“如果项目不在项目中”,它会停止任何重复的完整行,还是只是重复单个项目?如果是后者,如何防止重复行?)

【问题讨论】:

    标签: python csv scrapy


    【解决方案1】:

    对于您的Q2,我认为它不会阻止重复,因为它们是对象(类的实例)并且完全不同。你应该继承它并实现__eq__()

    您可以在使用csv 解析器检索所有元素后实现该目标,不是吗?

    另外,您可以将xpath 结果保存到变量中并检查它是否为空,例如:

    thing1 = list.select('h1/text()').extract()[0]
    if thing1.strip():
        ...
    

    此外,您可以使用额外的 xpath 表达式来检查您的文本是否都不会是空白的,例如:

    items = []
    for list in lists:
        if list.select('.[h1[text()] and h2[text()] and h3[text()]]'):
            item = TypeItem()
            item['thing1'] = list.select('h1/text()').extract()
            item['thing2'] = list.select('h2/text()').extract()
            item['thing3'] = list.select('h3/text()').extract()
            items.append(item)
    return(items) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-10
      • 2019-02-06
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多