Selenium无法点击谷歌链接表格SERP

时间:2015-09-17 13:20:06

标签: java selenium selenium-webdriver

这是测试的java类代码

public class Selenium_Test {

    @Test
    public void startWebDriver() {
        System.setProperty("webdriver.chrome.driver", "C:\\ChromeDriver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.navigate().to("https://www.google.com");
        Assert.assertEquals("Google", driver.getTitle());
        WebElement searchField = driver.findElement(By.cssSelector("input.gsfi"));
        searchField.sendKeys("datapine.com`");`
        searchField.submit();
        WebElement pricing = driver.findElement(By.linkText(".//a[text() = 'Pricing']"));
        List<WebElement> linkElements = driver.findElements(By.xpath("//*[@id='rso']/li"));

        for (WebElement result : linkElements) {
            if (result.equals(pricing)) {
                result.click();
            }
        }
    }
}

我总是得到Selenium在页面上找不到元素的错误。任何身体都能帮忙吗?

这是stacktrace:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"link text","selector":".//a[text() = 'Pricing']"}
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)

1 个答案:

答案 0 :(得分:1)

通过链接文本定位器应与链接文本一起使用,而不是XPath表达式。替换:

By.linkText(".//a[text() = 'Pricing']")

使用:

By.linkText("Pricing")

您可能还需要等待元素出现

WebDriverWait wait = new WebDriverWait(webDriver, 5);
WebElement pricing = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Pricing")));
pricing.click();