这是测试的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)
答案 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();