【问题标题】:White space and selectors空白和选择器
【发布时间】:2019-10-04 00:28:31
【问题描述】:

尝试使用 scrapy shell 上的选择器从网页中提取信息,但无法正常工作。我相信它的发生是因为类名中存在空格。知道出了什么问题吗?

我尝试了不同的语法,例如:

response.xpath('//p[@class="text-nnowrap hidden-xs"]').getall()

response.xpath('//p[@class="text-nnowrap hidden-xs"]/text()').get()

# what I type into my scrapy shell
response.css('div.offer-item-details').xpath('//p[@class="text-nowrap hidden-xs"]/text()').get()

# html code that I need to extract:
<p class="text-nowrap hidden-xs">Apartamento para arrendar: Olivais, Lisboa</p>

预期结果:Apartamento para arrendar:Olivais, Lisboa

实际结果:[]

【问题讨论】:

  • 类名中实际上没有空格。在 html 中,您可以通过在 class 属性中用空格分隔它们来为 html 元素提供多个类。这意味着

    有两个类:text-nowrap 和 hidden-xs。这可能会帮助您进一步调试问题。我自己快速搜索导致我找到以下解决方案,我自己没有测试:stackoverflow.com/a/3881148/6511985

  • 首先检查页面是否没有使用 JavaScript 向 HTML 添加元素。 Scrapy 无法运行 JavaScript,并且您的 HTML 可能与您预期的不同。
  • 感谢@StephanSchrijver 的帮助。这就是重点:类名没有空格。现在我需要知道如何使用“response.css()”选择器来提取包含空格的类名。做我的研究。谢谢!

标签: python scrapy


【解决方案1】:

class 部分的空格表示有多个类,“text-nnowrap”类和“hidden-xs”类。为了通过 xpath 选择多个类,可以使用以下格式:

"//element[contains(@class, 'class1') and contains(@class, 'class2')]"

(从How to get html elements with multiple css classes获取)

所以在你的例子中,我相信这会奏效。

response.xpath("//p[contains(@class, 'text-nnowrap') and contains(@class, 'hidden-xs')]").getall()

【讨论】:

    【解决方案2】:

    对于这种情况,我更喜欢使用 css 选择器,因为它的语法极简:
    response.css("p.text-nowrap.hidden-xs::text")

    当你观察 html 代码时,谷歌浏览器开发者工具也会显示 css 选择器
    这使得爬虫开发更容易

    【讨论】:

    • 完美@Georgiy。这就是我正在寻找的答案。谢谢!
    猜你喜欢
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多