简体   繁体   English

如何打印多个元素(div)及其值-Java中的Selenium WebDriver

[英]How to print multiple elements (div) & it values - Selenium WebDriver in java

1). 1)。 How can I get all element value in array/list? 如何获取数组/列表中的所有元素值?

2). 2)。 And How I click by value of the element? 以及如何按元素的值单击?

<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')]";

//this getSize() method work Correctly.! //此getSize()方法正常工作。

public int getSize() {
    waitUntilXXXButtonIsVisible();
    List<WebElement> count = getDriver().findElements(By.xpath(XPATH));
    return count.size();
}

How can I get all element value in array/list? 如何获取数组/列表中的所有元素值?

public String getAllListValue(){
    List<WebElement> list = getDriver().findElements(By.xpath(xpath));
    return list.toString();;
}

I tought, i will get String array like "5,10,20,50,75". 我坚强,我会得到像“ 5,10,20,50,75”这样的String数组。 :-) :-)

My second question is How can we click by div element value or div class Name(ChoiceEntry Choice_{index} )? 我的第二个问题是如何按div元素值或div类Name(ChoiceEntry Choice_ {index})单击?

Many thanks in advance. 提前谢谢了。

you will probably have to override the toString method if you want the output using your code. 如果要使用代码输出,则可能必须重写toString方法。

The simpler approach to achieve what you are trying to do is. 实现您要尝试的操作的更简单方法是。

    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));

As per your code if above line gives desired list size then use below code to fetch values 根据您的代码,如果上面的行给出了所需的列表大小,则使用下面的代码来获取值

for(WebElement element : listOfDivs)
{
    System.out.println(element.getText());
}

Code snippet for getting the list of values: 用于获取值列表的代码段:

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;
}

Code snippet for clicking on a selective choice: 单击选择的代码段:

//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.

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