处理动态Xpath值

时间:2014-12-08 12:20:25

标签: xpath selenium-webdriver

我有一个 Xpath = .//* [@ id ='select2-result-label-535'] 和 我使用下面的代码来处理相同的动态值,但这不起作用: -

for (int i=0; i<=9; i++) {

    String mpath = ".//*[@id='select2-result-label-535']"+i+"']";
    driver.findElement(By.xpath(mpath)).click();
    }

如果我做错了或有任何其他方法,请建议。

1 个答案:

答案 0 :(得分:0)

根据您上面给出的HTML代码段,您可以尝试以下任一代码从下拉列表中选择一个选项:

    //To click on the dropdown element
    WebElement select_drop = driver.findElement(By.id("select2-drop"));
    select_drop.click();

    //Get all the elements with role attribute as 'option'
    List<WebElement> options = select_drop.findElements(By.xpath("//*[@role='option']"));
    System.out.println("Number of clickable options in the dropdown: "+options.size());

    //To click on a specific option with certain text/innerHTML like 'reassign a transaction'
    for(WebElement option: options){
        if(option.getText().contains("reassign a transaction")){
            option.click();
            break;
        }
    }

[OR]

    WebElement select_drop = driver.findElement(By.id("select2-drop"));
    select_drop.click();

    //Get all the elements with role attribute as 'option'
    List<WebElement> options = select_drop.findElements(By.xpath("//*[@role='option']"));
    System.out.println("Number of clickable options in the dropdown: "+options.size());

    //To click on the first element in the dropdown
    options.get(0).click();

    //To click on the second element in the dropdown
    options.get(1).click();

    //To click on the third element in the dropdown
    options.get(2).click();

注意: - 您只能点击&#34; 0&#34;中的元素。上述代码的&#34; size-1&#34; 。除此之外将抛出 ArrayIndexOutOfBoundsException