英文:
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='submit'])[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.
<div>
<button class="submit" type="button"></button>
</div>
<div>
<button class="submit" type="button"></button>
</div>
<div>
<button class="submit" type="button"></button>
</div>
答案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<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();
}
If you are using Java 8 or above, you can try this way:
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();
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论