【问题标题】:How to select xpath only if a condition is satisfied仅在满足条件时如何选择 xpath
【发布时间】:2017-07-06 05:00:14
【问题描述】:

我的 HTML 如下所示:

div class = 'a-row a-spacing-small'
div class = 'a-row'

(它们在同一级别,我的意思是第二个div不是第一个div的孩子)(他们都是同一级别的父母)

我想从第一个div 的内部级别中选择href,其中class = 'a-row a-spacing-small' 仅当class = 'a-row' 满足条件的第二个div 的内部级别中的某些内容时。

我该怎么做?

任何想法

【问题讨论】:

  • 你能分享更详细的HTML吗?这是什么条件?

标签: python html xpath scrapy web-crawler


【解决方案1】:

所以对于您的 xpath,您希望从可以轻松识别的元素或根开始,在这种情况下,第一个 div 类是 'a-row a-spacing-small'

//div[@class='a-row a-spacing-small']

接下来将确定您的元素与该根元素的关系,因此在这种情况下,您需要一个href,它应该在a 中,并且应该在我们确定的div 中......但是你不确定它是否是一个直接的孩子..所以你使用//

//div[@class='a-row a-spacing-small']//a/@href

但是你只想要这个元素,如果它旁边的 div 满足条件..所以我们应该在我们已经创建的 xpath 之前的 xpath 开头放置一些东西......

//<somexpath>/div[@class='a-row a-spacing-small']//a/@href

但是什么xpath?我们所知道的是我们将第二个 div 设为根,因为它具有我们想要的条件......

//div[@class='a-row']

那么第一个div 与我们的新根有什么关系?它是preceding-sibling,因为它在新根之前并且在同一级别上。..

//div[@class='a-row']/preceding-sibling::div[@class='a-row a-spacing-small']//a/@href

现在无论条件是什么,我们都需要将它包含在根目录中...

//div[@class='a-row' and <condition>]/preceding-sibling::div[@class='a-row a-spacing-small']//a/@href

例子:

如果条件是 div 应该有一个带有文本“条件链接”的a//div[@class='a-row' and .//a[text()='conditional link']]/preceding-sibling::div[@class='a-row a-spacing-small']//a/@href

如果条件是 div 应该有一个 disabled 属性: //div[@class='a-row' and @disabled]/preceding-sibling::div[@class='a-row a-spacing-small']//a/@href

没有禁用属性怎么样? //div[@class='a-row' and not(@disabled)]/preceding-sibling::div[@class='a-row a-spacing-small']//a/@href

玩它...

【讨论】:

  • 当然,您还应该确定您所追求的是哪个href..就像a 中的文本“此链接”一样?在这种情况下://div[@class='a-row' and not(@disabled)]/preceding-sibling::div[@class='a-row a-spacing-small']//a[text()='this link']/@href
  • 非常感谢!很高兴实现这个=)
  • 来自未来的你好,到 2021 年这仍然有用
猜你喜欢
  • 2013-04-08
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 2011-12-28
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多