Selenium webdriver click google search

后端 未结 7 1051
情话喂你
情话喂你 2021-02-01 07:06

I\'m searching text \"Cheese!\" on google homepage and unsure how can I can click on the searched links after pressing the search button. For example I wanted to click the third

7条回答
  •  故里飘歌
    2021-02-01 07:53

    Google shrinks their css classes etc., so it is not easy to identify everything.

    Also you have the problem that you have to "wait" until the site shows the result. I would do it like this:

    public static void main(String[] args) {
    
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("Cheese!\n"); // send also a "\n"
        element.submit();
    
        // wait until the google page shows the result
        WebElement myDynamicElement = (new WebDriverWait(driver, 10))
                  .until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
    
        List findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
    
        // this are all the links you like to visit
        for (WebElement webElement : findElements)
        {
            System.out.println(webElement.getAttribute("href"));
        }
    }
    

    This will print you:

    • http://de.wikipedia.org/wiki/Cheese
    • http://en.wikipedia.org/wiki/Cheese
    • http://www.dict.cc/englisch-deutsch/cheese.html
    • http://www.cheese.com/
    • http://projects.gnome.org/cheese/
    • http://wiki.ubuntuusers.de/Cheese
    • http://www.ilovecheese.com/
    • http://cheese.slowfood.it/
    • http://cheese.slowfood.it/en/
    • http://www.slowfood.de/termine/termine_international/cheese_2013/

提交回复
热议问题