简体   繁体   中英

How to execute multiple key actions using webdriver with java

This is my code that opens a webpage and feeds input text into textfield and tries to browse further automatically. The first code: element.sendKeys(Keys.ENTER); is working but the next two lines immediately after this have no effect in my program. I am stuck here. Pls help me

public class GoogleSuggest {
    public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("vtu results");

        element.sendKeys(Keys.ENTER);

        element.sendKeys(Keys.TAB);
        element.sendKeys(Keys.Enter);


        System.out.println("Page title is: " + driver.getTitle());

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds

        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("v");
            }
        });

        System.out.println("Page title is: " + driver.getTitle());
    }
}

Not clear what all actions you want perform but following working for me. Try this out:

    driver.get("http://www.google.com");
    WebElement element = driver.findElement(By.name("q"));
    Actions action = new Actions(driver);
    element.sendKeys("result");
    action.sendKeys(element,Keys.ENTER).perform();
    action.sendKeys(Keys.TAB);
    Thread.sleep(2000);
    action.sendKeys(Keys.ENTER).perform();
    Thread.sleep(2000);
    System.out.println("Page title is: " + driver.getTitle());
    (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            return d.getTitle().toLowerCase().startsWith("R");
        }
    });

    System.out.println("Page title is: " + driver.getTitle());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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