【问题标题】:How to convert WebElement to a string for an 'if' statement in selenium/Java如何将 WebElement 转换为 selenium/Java 中“if”语句的字符串
【发布时间】:2019-08-04 09:46:21
【问题描述】:

我正在自动化 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();
        }

我尝试了几种不同的变体,将“这是必填字段”消息用作 Web 元素。不确定我是否需要以某种方式将消息的 WebElement 转换为字符串?或者包括一个布尔值?有人可以帮忙吗?

【问题讨论】:

  • sizeIsRequiredMsg 变量的返回类型是 WebElement,因此您无法将 WebElement 与 String 进行比较,因此您必须使用 sizeIsRequiredMsg.getText() 方法来获取文本,然后才能比较两个字符串。

标签: java string selenium if-statement automation


【解决方案1】:

尝试使用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);
};

希望对您有所帮助!

【讨论】:

  • 这确实运行了,但它仍然没有达到我想要的效果(单击大小小按钮)。无论如何谢谢:)
  • 'org.openqa.selenium.InvalidSelectorException:无效选择器:指定了无效或非法的选择器'
  • @golfumbrella 确保您导入 action = import org.openqa.selenium.interactions.Actions; 并创建一个新的 Action var = Actions action;
  • @golfumbrella 你可以像这样链接动作:action.moveToElement(sizeSmallButton).click().perform();
  • 是的,我已经完成了所有这些。我认为问题仍然在于阅读“这是必填字段”文本。我不确定我是否使用了正确的选择器,但似乎我都试过了
猜你喜欢
  • 2013-05-27
  • 2016-05-15
  • 1970-01-01
  • 2020-02-05
  • 2022-11-13
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多