ptstone
ptstone

Reputation: 558

Xpath in Selenium (chromedriver) wont match second tag

Trying to match a specific span on a website with selenium chromedriver (Version 79.0.3945.36 for Chrome 79) in java. The span heavily nested, but by itself simply:

    <span id="nodeval" title="Target XYZ ">Target XYZ </span>

I can successfully use text() or contains, but i would like to match the @title - if possible using starts-with (due to end changeing dynamically) but this i cannot get it to work correctly, even with just direct tag matching. Here is my test code test with contains, text, direct title and title using starts-with.

    String in_strChapterName = "Target XYZ ";
    List<WebElement> print = myDownloader.getWebDriver().findElements(By.xpath("//span[starts-with(@title,'"+in_strChapterName+"')]"));
    List<WebElement> print2 = myDownloader.getWebDriver().findElements(By.xpath("//span[contains(.,'" + in_strChapterName + "')]"));        
    List<WebElement> print3 = myDownloader.getWebDriver().findElements(By.xpath("//span[text()='" + in_strChapterName + "']"));        
    List<WebElement> print4 = myDownloader.getWebDriver().findElements(By.xpath("//span[@title='"+in_strChapterName+"']"));

    System.out.println("contains matches: "+print2.size());  //1 matches        
    System.out.println("text matches "+print3.size());       //1 matches

    System.out.println("starts-with title matches: "+print.size());  //0 matches
    System.out.println("direct title matches: "+print4.size());      //0 matches

Since i use example code (from here: https://www.guru99.com/xpath-selenium.html) almost 1:1 - only the tag isn't the first tag of the span - i wonder why the tag selection does not work for me...

Upvotes: 0

Views: 56

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193088

To match the title you can use the following Locator Strategy:

String in_strChapterName = "Target XYZ";
List<WebElement> print4 = myDownloader.getWebDriver().findElements(By.xpath("//span[contains(@title, '" +in_strChapterName+ "')]"));
System.out.println("direct title matches: "+print4.size()); //1 match

Upvotes: 1

Related Questions