2

I have this HTML:

<div>
    <!-- \/ this div -->
    <div>
        aaa
        <!-- -->
        bbb
    </div>
</div>

I want to select the second div like this: "//div[contains(text(), 'bbb')]", but selenium don't find it.

I tested this:

System.out.println(
    driver.findElement(By.xpath("//div[contains(text(), 'aaa')]")).getText()
); //aaa bbb

System.out.println(
    driver.findElement(By.xpath("//div[contains(text(), 'bbb')]")).getText()
); //Unable to locate element:...

Why don't find element if I looking for text which is after a comment?

KunLun
  • 3,109
  • 3
  • 18
  • 65

1 Answers1

4

You can use:

System.out.println(
    driver.findElement(By.xpath("//div[contains(., 'bbb')]")).getText()
);

For more info see this answer

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
  • Hmm...It's not perfect. For `
    aaabb
    `, I get first div. Which is parent of `div` I want. In a real page give me the `div` which is nearest to root(``) and have a subnode with `bbb`. I updated my question html.
    – KunLun Sep 19 '19 at 11:47
  • @KunLun can you share more of the HTML or the URL? this is a new question... I'd like to help... – Moshe Slavin Sep 19 '19 at 11:50
  • I updated html from question. With your xpath I get first div. – KunLun Sep 19 '19 at 11:53
  • You will have to give a more explicit path... for example `"//div/descendant::div[contains(., 'bbb')]"` – Moshe Slavin Sep 19 '19 at 11:57