点击特定实例以使用 CSS 选择器选择按钮。

huangapple go评论70阅读模式
英文:

Click on particular instance for a button using CSS selector

问题

我有一个网页,上面有多个提交按钮。我想循环遍历它们,逐个点击。

我知道可以通过XPath这样做:(//button[@class='submit'])[i](其中i是循环次数)。

但我想知道是否可以通过CSS选择器来实现?

我尝试过 button.submit,但它总是点击第一个按钮,我想要能够循环遍历。我还尝试过 button.submit:first-child,但似乎效果一样。

以下是HTML的类似部分:

<div>
    <button class="submit" type="button"></button>
</div>
<div>
    <button class="submit" type="button"></button>
</div>
<div>
    <button class="submit" type="button"></button>
</div>
英文:

I have a webpage which has multiple submit buttons. I want to loop through them and click on each of them one by one.

I know I can do it via xpath like this (//button[@class=&#39;submit&#39;])[i] (where i = loop number).

But I wanted to know if it's possible to do via CSS selector?

I've tried button.submit but it will always click on the first button and I want to be able to loop through. I've also tried button.submit:first-child but it seems to do the same thing.

The following is similar to what the HTML is like.

&lt;div&gt;
    &lt;button class=&quot;submit&quot; type=&quot;button&quot;&gt;&lt;/button&gt;
&lt;/div&gt;
&lt;div&gt;
    &lt;button class=&quot;submit&quot; type=&quot;button&quot;&gt;&lt;/button&gt;
&lt;/div&gt;
&lt;div&gt;
    &lt;button class=&quot;submit&quot; type=&quot;button&quot;&gt;&lt;/button&gt;
&lt;/div&gt;

答案1

得分: 1

是的,你可以这样做:

如果你使用的是低于Java 8的版本,可以这样操作:

List<WebElement> elements = driver.findElements(By.cssSelector("button.submit"));

WebElement confirm = driver.findElement(By.cssSelector("selector_for_confirm"));

for(WebElement element: elements){
     element.click();
     confirm.click();
}

如果你使用的是Java 8或更高版本,可以尝试以下方式:

List<WebElement> elements = driver.findElements(By.cssSelector("button.submit"));

WebElement confirm = driver.findElement(By.cssSelector("selector_for_confirm"));

  elements.forEach(e->{
        e.click();
        confirm.click();
    });
英文:

Yes, you can do this such way:

If you are using Java version less than 8 do this way:

List&lt;WebElement&gt; elements = driver.findElements(By.cssSelector(&quot;button.submit&quot;));

WebElement confirm = driver.findElement(By.cssSelector(&quot;selector_for_confirm&quot;));

for(WebElement element: elements){
     element.click();
     confirm.click();
}

If you are using Java 8 or above, you can try this way:

List&lt;WebElement&gt; elements = driver.findElements(By.cssSelector(&quot;button.submit&quot;));

WebElement confirm = driver.findElement(By.cssSelector(&quot;selector_for_confirm&quot;));

  elements.forEach(e-&gt;{
        e.click();
        confirm.click();
    });

huangapple
  • 本文由 发表于 2020年7月24日 03:17:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63061625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定