简体   繁体   English

如何从Java和Selenium中的元素列表中获取元素中的元素

[英]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: 在我的代码中,我使用它来获取汽车的WebElement列表:

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: 然后,获取第5辆车的WebElement,并找到这辆车的选择按钮:

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)? 是否可以仅在此特定元素中定位按钮和其他元素(仅将Webdriver限制为该元素)?

Just create a locator to the button for each car. 只需为每辆车的按钮创建一个定位器。

With the List<WebeElement> find all buttons and click them by index. 使用List<WebeElement>查找所有按钮,然后按索引单击它们。 list.get(1).click();

Second solution is to create xpath locator for each button. 第二种解决方案是为每个按钮创建xpath定位器。

First car 第一辆车

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

Locate your webElement 找到您的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. 到Xpath。 @Grasshopper solution worked. @Grasshopper解决方案有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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