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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将WebElement转换为selenium / Java中'if'语句的字符串相关的知识,希望对你有一定的参考价值。

我正在使用selenium / Java自动化一个webstore。如果用户未选择产品的大小,则会显示一条消息,指出大小旁边的“这是必填字段”。我正在尝试编写一个'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();
        

我使用'this is a required field'消息作为web元素尝试了一些不同的变体。不知道我是否需要以某种方式将消息的WebElement转换为字符串?或者包含一个布尔值?有人可以帮忙吗?

答案

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

希望这对你有所帮助!

以上是关于如何将WebElement转换为selenium / Java中'if'语句的字符串的主要内容,如果未能解决你的问题,请参考以下文章

在Java中使用Selenium 2将鼠标悬停在WebElement上[重复]

Selenium:我可以在 Selenium 中设置 WebElement 的任何属性值吗?

如何解决TypeError:'WebElement'类型的对象在Python Selenium中没有len()

在 Python 中打印 selenium webelement 的 HTML 文本

selenium与页面交互之二:webelement类的属性

selenium.webdriver.remote.webelement.WebElement解析