无法通过selenium网络驱动程序(Java)点击谷歌的搜索结果

时间:2016-09-01 07:55:45

标签: selenium-webdriver webdriver

我试图在谷歌搜索一些东西,让我们说“测试”。所以我想点击第一个搜索结果,但无法做到。请在下面找到我的代码。我尝试过使用xpath,class和cssSelector。请帮忙。:

/**
 * @param args
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub

    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.google.co.in/");

    driver.findElement(By.id("lst-ib")).sendKeys("Testing" + Keys.ENTER);
    Thread.sleep(5);

    driver.findElement(
            By.className("r"))
            .click();
}

请同时找到Inspect Element结果:

软件测试 - 维基百科,免费的百科全书

2 个答案:

答案 0 :(得分:0)

尝试一次提供链接的位置而不是标题

xpath= //h3[@class='r']/a

如果您只打算点击​​第一个链接,那么上面的路径工作。

如果要单击特定元素,请尝试构建返回特定元素的xpath。例如,点击维基百科链接

xapth=//a[@href='https://en.wikipedia.org/wiki/Software_testing']

您也可以尝试

1.collecting all links into List and 
2. iterating one by one
3. By using getText get text and verify required one
4. once condition satisfy then click on it.

答案 1 :(得分:0)

您应该尝试使用WebDriverWait等待元素可见并启用以下点击: -

driver.get("https://www.google.co.in/");

driver.findElement(By.id("lst-ib")).sendKeys("Testing" + Keys.ENTER);

new WebDriverWait(driver, 10)
                .until(ExpectedConditions.elementToBeClickable(By
                        .linkText("Software testing - Wikipedia, the free encyclopedia"))).click();