Java和Selenium显示Google搜索结果的最佳方式

时间:2016-09-06 15:52:33

标签: java selenium selenium-webdriver

我对Selenium和Java很新,但我正在尝试制作一个加载谷歌的简单程序,进行搜索,然后显示加载谷歌搜索需要多少结果和多长时间。我遇到了结果问题,并将其显示

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;
import org.openqa.selenium.WebElement;

public class GoogleSearch {

public static void main(String[] args) {

    FirefoxDriver driver = new FirefoxDriver();
    driver.get("http://google.com");


    WebElement searchTextBox = driver.findElement(By.id("lst-ib"));
    searchTextBox.sendKeys("Colin");

    String pageUrl = driver.getCurrentUrl();
    System.out.println(pageUrl);

    WebElement searchButton = driver.findElement(By.className("lsb"));
    searchButton.click();

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


    WebDriverWait wait = new WebDriverWait(driver, 5);// 5 seconds 
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("resultsStats")));
    driver.findElement(By.id("resultsStats"));

    WebElement results = driver.findElement(By.id("resultsStats")); //displays # of results from search
        System.out.println(results);

    //driver.quit();


}
}

以下是我得到的结果:

https://www.google.com/?gws_rd=ssl
Page title is:Google
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"resultsStats"}
Command duration or timeout: 13 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'

1 个答案:

答案 0 :(得分:1)

不是 resultsStats ,它是 resultStats 。改变一样,你就好了!

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("resultStats")));
driver.findElement(By.id("resultStats"));

WebElement results = driver.findElement(By.id("resultStats")); //displays # of results from search

resultStats