如何在Selenium / Java中将WebElement转换为'if'语句的字符串

时间:2019-03-13 16:17:22

标签: java string selenium if-statement automation

我正在用selenium / Java自动化网络商店。如果用户尚未选择产品尺寸,则会出现一条消息,指出尺寸旁边的“这是必填字段”。我正在尝试写一个'if'语句,断言该消息是否存在以及是否存在该消息,但我无法使其正常工作。可能是这样的:

 WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector("#advice-required-entry-select_30765)"));
 WebElement sizeSmallButton = driver.findElement(By.cssSelector("#product_info_add > div.add-to-cart > div > button"))

          if (sizeIsRequiredMsg.equals("This is a required field.")) {
              action.moveToElement(sizeSmallButton);
              action.click();
              action.perform();
        }

我尝试使用“这是必填字段”消息作为网络元素尝试了几种不同的变体。不确定是否需要将消息的WebElement转换为字符串?还是包含布尔值?有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

尝试使用getText()这样的东西:

编辑,我添加了正确的cssSelectors并添加了try catch

WebElement addToCartButton = driver.findElement(By.cssSelector("#product_info_add  button")); 
action.moveToElement(addToCartButton); 
action.click(); 
action.perform(); 

try {
    WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector(".validation-advice"));
    WebElement sizeSmallButton = driver.findElement(By.cssSelector(".swatches-container .swatch-span:nth-child(2)"))
    if (sizeIsRequiredMsg.getText() == "This is a required field.") {
          action.moveToElement(sizeSmallButton);
          action.click();
          action.perform();
    }

} catch (Exception e) {
    System.out.println(e);
    logger.log(Level.SEVERE, "Exception Occured:", e);
};

希望这对您有帮助!