Selenium webdriver点击谷歌搜索 [英] Selenium webdriver click google search

查看:314
本文介绍了Selenium webdriver点击谷歌搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索文本奶酪!在谷歌主页上,不确定如何在按下搜索按钮后点击搜索到的链接。例如,我想在搜索页面上单击顶部的第三个链接,然后如何找到标识链接并单击它。到目前为止我的代码:

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 link from top on search page then how can I find identify the link and click on it. My code so far:

package mypackage;

import org.openqa.selenium.By; 

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.chrome.ChromeDriver; 
import org.openqa.selenium.support.ui.WebDriverWait;

public class myclass {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-2.35.0\\chromedriver_win32_2.2\\chromedriver.exe");

         WebDriver driver = new ChromeDriver(); 
         driver.get("http://www.google.com"); 
         WebElement element = driver.findElement(By.name("q"));
         element.sendKeys("Cheese!");
         element.submit();

         //driver.close();
    }



}


推荐答案

谷歌缩小了他们的CSS课程等,所以要识别所有内容并不容易。

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<WebElement> 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"));
    }
}

这将打印出来:

  • 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/

这篇关于Selenium webdriver点击谷歌搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆