xpathselenium-webdriverjava-7

findelement is not throwing NoSuchElementException


I want to write a test to check if a webelement with a specified text is not present on a page. This is the code for the method doing the job:

public boolean checkOfAanvraagIsOpgevoerd (String titel)
{
    
    String quote = "\"";
    String titelMetQuotes = quote + titel +quote;
    titelMetQuotes = "dierdieboeboe";
    boolean isOpgevoerd=false;
    try {
        driver.findElement(By.xpath(".//*[@id='listRequests']//h4/a[contains(text(),"+titelMetQuotes+")]"));
        isOpgevoerd=true;
    } catch (NoSuchElementException NE) {
        NE.printStackTrace();
    }
    return isOpgevoerd;
}

Although I'm absolutely sure that there is not a tag on the page which contains the text "dierdieboeboe" still the catch block is skipped. When I replace for instance h4 in h5 in the xpath expression the NoSuchElementException is thrown as expected. It seems that the contains part in the expression is ignored.


Solution

  • Try this (note the single quotes around the actual text):

    By.xpath("//*[@id='listRequests']//h4/a[contains(text(),'"+titelMetQuotes+"')]")
    

    contains is a function that takes two strings. Hence the text of your variable titelMetQuotes needs to be quoted. Obviously, in this case it is easier to use single quotes.

    Additionally, the variable name (titel with quotes) is quite misleading because it actually has no quotes for another flaw in the code:

    String titelMetQuotes = quote + titel +quote;
    titelMetQuotes = "dierdieboeboe";
    

    The second line simply overwrites the quoted title with a non quoted string.

    Finally, you don't need the leading dot in your xpath expression in order to locate the first element of any kind with id listRequests