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

标签 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 转换为字符串?或者包含一个 boolean 值?有人可以帮忙吗?

最佳答案

尝试使用像这样的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);
};

希望这对您有帮助!

关于java - 如何在 selenium/Java 中将 WebElement 转换为 'if' 语句的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146583/

相关文章:

java - UUID 缩短

javascript - 为什么这段 JavaScript 代码在 Firefox 中无效?

python - 将字节转换为字符串

java - 在 Eclipse 中运行 Selenium 时在哪里可以找到 System.out.println 输出?

java - OkHttp 每个请求超时设置?

java - Stripes UrlBinding - 参数在提交时消失

java - Hibernate : java. lang.ClassCastException : java. lang.Integer 无法转换为 java.lang.Double

Java split() 正则表达式

selenium - 涉及开始的 Xpath 不起作用

c# - 如何使用 Selenium 从 HTML5 数据列表中进行选择