I'm trying to learn Selenium on Java, can't for the life of me figure out why xpath contain can't find the right element.
Here's the whole case:
@Test
public void test1_FluentWait() {
driver.get("https://www.google.com");
WebElement searchBar = driver.findElement(By.xpath("//input[contains(@name, 'q')]"));
searchBar.sendKeys("Selenium", Keys.ENTER);
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement element = fluentWait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver w) {
// WebElement ele = w.findElement(By.xpath("//*[contains(text(), 'Selenium - Health Professional')]")); // Doesn't work, no idea why
WebElement ele = w.findElement(By.partialLinkText("Selenium - Health Professional")); // works
// WebElement ele = w.findElement(By.xpath("//*[text()='Selenium - Health Professional']"));
// WebElement ele = w.findElement(By.xpath("//*[contains(@href, 'Selenium-HealthProfessional')]")); // Found attribute, can't click
if (ele.isEnabled()) {
System.out.println("Found");
}
return ele;
}
});
System.out.println(element.getText());
// element.click();
}
Here's the element in question
So basically, only the partialLinkText works when finding this element.
WebElement ele = w.findElement(By.xpath("//*[contains(text(), 'Selenium - Health Professional')]")); // Doesn't work, no idea why
WebElement ele = w.findElement(By.partialLinkText("Selenium - Health Professional")); // works
WebElement ele = w.findElement(By.xpath("//*[text()='Selenium - Health Professional']"));
contains text() prints "found" but the returned element's getText() prints empty string. click() throws ElementNotInteractableException
text()='...' throws NoSuchElementException
partialLinkText returns the element and allows click()
What am I doing wrong? What is the issue here? How can I prevent this or know in the future which findElement to use?