如何将WebElement转换为';如果';selenium/Java中的语句

如何将WebElement转换为';如果';selenium/Java中的语句,java,string,selenium,if-statement,automation,Java,String,Selenium,If Statement,Automation,我正在用selenium/Java自动化一个Web存储。如果用户尚未选择产品的尺寸,则会在尺寸旁边出现一条消息,说明“这是必填字段”。我试图写一个“如果”语句,断言此消息是否存在,以及如果存在则要采取的操作,但我无法使其工作。它将是这样的: WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector("#advice-required-entry-select_30765)")); WebElement sizeSmall

我正在用selenium/Java自动化一个Web存储。如果用户尚未选择产品的尺寸,则会在尺寸旁边出现一条消息,说明“这是必填字段”。我试图写一个“如果”语句,断言此消息是否存在,以及如果存在则要采取的操作,但我无法使其工作。它将是这样的:

 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();
        }
我尝试了几种不同的变体,将“thisarequired字段”消息用作web元素。不确定是否需要以某种方式将消息的WebElement转换为字符串?或者包含布尔值?有人能帮忙吗?

试着使用
getText()
类似的方法:

编辑我添加了正确的CSS选择器,并添加了
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);
};

希望这对你有帮助

sizeIsRequiredMsg变量的返回类型是WebElement,因此您无法将WebElement与字符串进行比较,因此必须使用sizeIsRequiredMsg.getText()方法来获取文本,然后您可以比较两个字符串。此操作现在确实运行,但它仍然不符合我的要求(单击“小尺寸”按钮)。无论如何感谢:)'org.openqa.selenium.InvalidSelectorException:无效选择器:指定了无效或非法的选择器'@golfumbrella确保导入操作=
import org.openqa.selenium.interactions.Actions
并创建一个新的Action var=
Actions Action
@golfumbrella您可以像这样链接操作:
action.moveToElement(sizeSmallButton)。单击().perform()