简体   繁体   中英

How do I get the second element which matches a wildcard css selector?

I have a page with two buttons share the similar id in the pattern of button A id be "ABCNN_xxx" and button B id be "ABC(NN+1)_xxx" which NN is a number that being different on other pages with the same logic. My script needs to get those button universally on different pages so I use a wildcard css selector. However, since the two buttons share the same pattern, the wildcard selector would catch only the first button (A, with smaller NN number) it sees but cannot locate the second one.

I tried to put [2] behind the selector but seems it doesn't work like that. I am using the below css selector. It will get me the first match but not the remaining match.

driver.findElement(By.cssSelector("img[id^='ABC'][id$='_xxx']")).click();

Besides getting me ABC36_xxx for the first time, I would like to have ABC37_xxx for the second call instead of returning the first result. How should I achieve my objective?

you could select all into an array and loop over them using findElement s : driver.findElements(By.cssSelector("img[id^='ABC'][id$='_xxx']")).click(); Or you could add a flag class after clicking it:

  • after the click add a "seleniumClicked" class to the button
  • then change your selector to driver.findElements(By.cssSelector("img[id^='ABC'][id$='_xxx']:not(.seleniumClicked)")).click();

If you sure with the locator : By.cssSelector("img[id^='ABC'][id$='_xxx']") and it more than one, then collect them by :

List<WebElement> elmnts = driver.findElements(By.cssSelector("img[id^='ABC'][id$='_xxx']"));

And this to get second element :

elmnts.get(1).click();

Import this :

import java.util.List;
import org.openqa.selenium.WebElement;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM