简体   繁体   English

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

[英]How to convert WebElement to a string for an 'if' statement in selenium/Java

I'm automating a webstore in selenium/Java. 我正在使用selenium / Java自动化网络商店。 If the user hasn't selected the size of a product, a message comes up stating 'this is a required field' next to the size. 如果用户尚未选择产品尺寸,则会出现一条消息,指出尺寸旁边的“这是必填字段”。 I'm trying to write an 'if' statement that asserts whether this message is present and the action to take if it is, but I cannot get it to work. 我正在尝试写一个'if'语句,断言该消息是否存在以及是否存在该消息,但我无法使其正常工作。 It would be something along the lines of this: 可能是这样的:

 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();
        }

I've tried a few different variations using the 'this is a required field' message as a web element. 我已尝试使用“这是必填字段”消息作为网络元素尝试了几种不同的变体。 Not sure if I need to convert the WebElement for the message to a string somehow? 不确定是否需要将消息的WebElement转换为字符串? Or include a boolean? 还是包含布尔值? Can anyone help? 有人可以帮忙吗?

Try using getText() something like this: 尝试使用getText()这样的东西:

EDIT I have added the correct cssSelectors and added try catch : 编辑我已经添加了正确的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);
};

Hope this helps you! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM