【问题标题】:Select tag which meets a condition [duplicate]选择符合条件的标签[重复]
【发布时间】:2015-08-30 19:53:38
【问题描述】:

我对 css 选择器很陌生,我正在尝试这样做:

我有一个 html 和多个 divs。我想选择第一个满足某些条件的div,比如说div[id*='ample'],然后选择所有具有相同条件的divs,但不是第一个divs 孩子。

<div id="example1">
    <div id="example2">
    </div>
</div>
<div id="example3">
</div>

所以我想要得到divid='example1'id='example3'。 最好的情况是,例如 divid='example3' 不必是第一个 divs 兄弟。

你知道怎么做吗?

我在想:

div = css_select("div[id*='ample')")
while True: 
   divs.append(div)
   div = div + css_select("div[id*='ample')")

但它可能一文不值。

【问题讨论】:

  • 你应该避免使用 id's 来达到这个目的,它们不应该以这种方式工作,考虑使用类(你可能知道这一点)
  • 你应该编辑这个问题而不是reposting it

标签: html parsing selenium selenium-webdriver css-selectors


【解决方案1】:

在 JavaScript 中有很多选择元素的方法,这取决于 html。

回到您的问题:您可以通过使用这些 div 的父级(例如 body)来做到这一点

NodeList.prototype.forEach = Array.prototype.forEach;


/* 'body > *[id*="ample"]' - you can replace the 'body' selector with other parent selector */
document.querySelectorAll('body > *[id*="ample"]').forEach(function(el) {
    el.classList.add('red');
});
div {
  height:10px;  
  border:1px solid #000;
}

.red {
  border:1px solid red;
}
<div id="example1">
    <div id="example2">
    </div>
</div>
<div id="example3">
</div>

【讨论】:

  • 这对我不起作用,因为 div 不必是 body 的孩子,也可以是孙子等。
猜你喜欢
  • 2013-07-10
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多