How can I extract the text of HTML5 Constraint val

2020-04-20 18:56发布

问题:

I have tried switch to alert but it's showing no such alert found error. And i have also tried ifranes,windowhandling. The popup stays for only 1-2 sec and I can't use inspect element to get the xpath of that. Please check the scrrenshot attached.

回答1:

The alert window in https://www.phptravels.net/ which you are referring is the outcome of Constraint API's element.setCustomValidity() method.

Note: HTML5 Constraint validation doesn't remove the need for validation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad guys trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side.

Solution

To retrieve the text which results out from the element.setCustomValidity() method, you can use the following solution:

  • Code Block:

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.openqa.selenium.By;
    
    public class HTML5_input_field_validation_message {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();
            driver.get("https://www.phptravels.net/");
            WebElement checkin = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form.input-lg.dpd1[name='checkin']")));
            System.out.println(checkin.getAttribute("validationMessage"));
        }
    }
    
  • Console Output:

    Please fill out this field.
    


回答2:

There is possibility we perform mouse actions and move the mouse towards the element, when the mouse pointer moves on to the element then we will get the tool tip text.

  1. So, get the locator values of the element and tooltip text.
  2. Move the mouse pointer to element using element locator.
  3. create webelement object for tooltip text and get text.