XPath contains(text(), 'string') does not work, but partialLinkText('sameString') works



  • 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 Google Search's element

    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?



  • There is a possibility that there are found more than one webelement which are matching the xpath criteria. A way to find it out is use findElements with xpath and check the count of list.

    when we use findElement the first match is returned, which could be an element which is not workable or the link.

    When you use partialLinkText it knows it has to find a link and match with partial text.

    please check this.

    hope it helps.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2