简体   繁体   中英

How to get element in element from the list of elements in Java and Selenium

On the page I have, for example, list of cars, all of them have the same buttons, like "select" (locators are the same for all select buttons):

In my code, I'm using this to get the list of WebElements for cars:

List<WebElement> allCars = driver.findElements(By.Xpath(ListOfAvailableCars));

Then, I'm getting WebElement for 5th car and I'm locating select button for this car:

allCars.get(4).findElement(By.Xpath(SelectButtonLocator)).click();

But "select" button pressed for the 1st car in the list.

Is it possible to just locate button and other elements in this particular element (to restrict Webdriver to this element only)?

Just create a locator to the button for each car.

With the List<WebeElement> find all buttons and click them by index. list.get(1).click();

Second solution is to create xpath locator for each button.

First car

driver.findElement(By.xpath("(//button[@id='something'])[1]")).click();

Locate your webElement

List<WebElement> allCars = driver.findElements(By.Xpath(ListOfAvailableCars)/following-sibling::SelectButtonLocator);

then

allCars.get(4).click()

hope it will help. if possible, please share the screenshot

Thanks to all!

Solved this problem by adding "." to the Xpath. @Grasshopper solution worked.

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