![](/img/trans.png)
[英]How to get multiple elements (div) using Xpath Selenium WebDriver JAVA?
[英]How to print multiple elements (div) & it values - Selenium WebDriver in java
1)。 如何获取数组/列表中的所有元素值?
2)。 以及如何按元素的值单击?
<div class="Choice" style="margin-top: -483px;>
<div class="ChoiceEntry Choice_1"> 5</div>
<div class="ChoiceEntry Choice_3"> 10</div>
<div class="ChoiceEntry Choice_2"> 20</div>
<div class="ChoiceEntry Choice_4"> 50</div>
<div class="ChoiceEntry Choice_7"> 75</div>
<div>...</div>
</div>
private static String choiceXPATH =
".//div[@class='Choice']//div[contains(@class,'ChoiceEntry')]";
//此getSize()方法正常工作。
public int getSize() {
waitUntilXXXButtonIsVisible();
List<WebElement> count = getDriver().findElements(By.xpath(XPATH));
return count.size();
}
如何获取数组/列表中的所有元素值?
public String getAllListValue(){
List<WebElement> list = getDriver().findElements(By.xpath(xpath));
return list.toString();;
}
我坚强,我会得到像“ 5,10,20,50,75”这样的String数组。 :-)
我的第二个问题是如何按div元素值或div类Name(ChoiceEntry Choice_ {index})单击?
提前谢谢了。
如果要使用代码输出,则可能必须重写toString方法。
实现您要尝试的操作的更简单方法是。
List<WebElement> list = driver.findElements(By.xpath(xpath));
Iterator<WebElement> iterator = list.iterator();
List<String> values = new ArrayList<String>();
while (iterator.hasNext()){
WebElement element = iterator.next();
values.add(element.getText());
}
System.out.println(values.toString());
List<WebElement> listOfDivs = getDriver().findElements(By.xpath(xpath));
根据您的代码,如果上面的行给出了所需的列表大小,则使用下面的代码来获取值
for(WebElement element : listOfDivs)
{
System.out.println(element.getText());
}
用于获取值列表的代码段:
public List<String> getAllListValues(){
List<WebElement> items = driver.findElements(By.cssSelector("div[class^='ChoiceEntry Choice_']"));
List<String> valuesOfChoices = new ArrayList<String>();
for(WebElement item : items){
valuesOfChoices.add(item.getText());
}
return valuesOfChoices;
}
单击选择的代码段:
//position of the choice is not 0-based
public void getAllListValues(int positionOfTheChoice){
driver.findElement(By.cssSelector("class='ChoiceEntry Choice_"+positionOfTheChoice+"'")).click();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.