Java:尝试获取HTML元素的值

时间:2018-06-27 10:30:55

标签: java selenium for-loop if-statement automation

我正在尝试从网站中提取HTML表格元素的值,并将其与用户输入的值进行比较,但是当我运行程序时,似乎没有输入嵌套循环。它工作正常,没有错误,但是我没有从Eclipse得到任何输出,我是Selenium Java的新手,并且还在学习。

请参见下面的代码:

String inputString = basePrem;
try {

    //Print to console the value of Base Prem
    WebElement table = driver.findElement(By.xpath(".//td[text()='Base Premium']/following-sibling::*"));
    List<WebElement> allrows = table.findElements(By.tagName("tr"));
    List<WebElement> allcols = table.findElements(By.tagName("td"));    

    for (WebElement row: allrows) {
        List<WebElement> Cells = row.findElements(By.tagName("td"));
            for (WebElement Cell:Cells) {
                if (Cell.getText().contains(basePrem)) {
                    System.out.print("Base Premium = "+ basePrem + "   ");
                }
                else if (!Cell.getText().contains(basePrem))
                {
                    System.out.print("Base Premium = " + basePrem + " ");
                    break;
                }
            }
        }
    }
catch (Exception e) {
    errorMessage = "Value discrepancy";
    System.out.println(errorMessage + " - " + e.getMessage());
    driver.close();
}

此外, inputString 是我输入用于比较的值的地方(我使用单独的excel文件进​​行测试)

由于控件没有进入嵌套循环,我可能有一些逻辑错误?

1 个答案:

答案 0 :(得分:0)

您可以重写下面的代码,然后验证表中是否提供您的输入字符串。不必使用嵌套的循环

代码:

    String inputString = basePrem;

    WebElement table = driver.findElement(By.xpath(".//table"));
    //Extract all the Cell Data Element
    List<WebElement> dataElementList=table.findElements(By.xpath(".//td"));

    for(WebElement dataElement : dataElementList){

        if(dataElement.getText().contains(inputString)){
            System.out.print("Base Premium = "+ basePrem + "   ");
            break;
        }
    }