【问题标题】:normalize-space just works with xpath not css selectornormalize-space 仅适用于 xpath 而不是 css 选择器
【发布时间】:2014-02-02 19:26:16
【问题描述】:

我正在使用 scrapy 和 python 提取数据。

数据有时包含空格。我使用 normalize-space 和 xpath 来删除这些空格,如下所示:

xpath('normalize-space(.//li[2]/strong/text())').extract()

这句话非常好。但是,现在我想将 normalize-space 与 css 选择器一起使用。

我试过这个:

car['Location'] = site.css('normalize-space(div[class=location]::text)').extract()

如果我删除了规范化空间,我得到了正确的结果,但我得到了空结果..

请问如何将它与 css 选择器一起使用?

我试过了

def normalize_whitespace(str):
        import re
        str = str.strip()
        str = re.sub(r'\s+', ' ', str)
        return str

我这样称呼这个函数:

car['Location'] = normalize_whitespace(site.css('div[class=location]::text').extract())

但我得到了空的结果。请问为什么?

【问题讨论】:

  • .extract() 返回一个 unicode 字符串列表。而这个normalize_whitespace 将一个unicode 字符串作为输入。所以你需要要么使用.extract()[0](如果你知道你希望列表中只有1个字符串结果),或者你可以使用u''.join(site.css('div[class=location]::text').extract())序列化unicode字符串列表
  • @pault。这只是一个字符串结果。但我得到了空结果,请检查我的代码
  • 你在.extract()之后添加了[0]吗?
  • @pault。我在我的代码中做错了什么,所以我得到了空结果。也正如我告诉你的那样。如果我删除了该函数的调用,我得到了整个数据
  • 在你的蜘蛛类之外定义normalize_whitespace

标签: python css python-2.7 xpath scrapy


【解决方案1】:

很遗憾,Scrapy 中的 CSS 选择器不支持 XPath 函数。

您可以先将div[class=location]::text CSS 选择器转换为等效的XPath 表达式,然后将其包装在normalize-space() 中作为.xpath() 的输入。

无论如何,由于您只对最终的“空白规范化”字符串感兴趣,因此您可以在 CSS 选择器提取的输出上使用 Python 函数来实现相同的目的。

例如见http://snipplr.com/view/50410/normalize-whitespace/:

def normalize_whitespace(str):
    import re
    str = str.strip()
    str = re.sub(r'\s+', ' ', str)
    return str

如果你在你的 Scrapy 项目中包含这个函数,你可以像这样使用它:

    car['Location'] = normalize_whitespace(
        u''.join(site.css('div[class=location]::text').extract()))

或

    car['Location'] = normalize_whitespace(
        site.css('div[class=location]::text').extract()[0])

【讨论】:

  • 我喜欢你说的那个页面,请问在我的情况下如何使用该功能?另外,我总是谢谢你。你总是在 python 和 scrapy 方面帮助我。 +1
  • 不客气,这就是 StackOverflow 的意义所在。我添加了一个示例,说明如何使用 Python 函数通过 CSS 选择器 .extract() 结果的输出来规范化空格
  • 我也尝试了您编辑的解决方案,但得到一个空结果。也许我添加的功能错误?
  • 我试过你的解决方案但得到一个空结果,请检查我在问题中的所有代码。如果我删除了空白函数的调用,代码运行良好,但添加该函数时返回空结果
【解决方案2】:

css() 编译一个 xpath,因此您可以将它链接到一个 xpath() 规范化空格,因此将您的代码更改为:

car['Location'] = site.css('normalize-space(div[class=location])').xpath('normalize-space(text())').extract()

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 2019-04-13
    • 1970-01-01
    • 2014-05-29
    • 2021-04-14
    • 2010-12-22
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多