1

How do I use the XPath substring function in the Chrome inspector? I can't create a working example in the inspector's Elements tab.

For example, this selector:

//div[contains(text(),'Man')]

works on this page, but

substring(//div[contains(text(),'Man')], 2)

fails to select anything. Shouldn't it continue to select the same element as the first selector?

Ultimately I'm passing the second selector to the JavaScript document.evaluate() function in order to get a piece of the text() string. As of now document.evaluate() is not returning anything for the second selector.

PS. I read this question and this one but they don't mention using the Chrome inspector.

prevail
  • 33
  • 2
  • I've tried `document.evaluate("substring(//div[contains(text(),'Man')], 2)", document)`. Works fine, returns `XPathResult {resultType: 2, stringValue: "Managing Partner, Fort Worth Office↵↵", invalidIteratorState: false}` – qwermike Nov 12 '18 at 08:20
  • What about in the Chrome inspector? – prevail Nov 12 '18 at 08:48
  • Yea, in inspector(Ctrl+F) does not work :( – qwermike Nov 12 '18 at 09:16

1 Answers1

0

Seems that in Chrome inspector (using search within DOM - Elements tab) you can't highlight the text only or part of it.

For example, if you try //div[contains(text(),'Man')]/text(), you'll get the whole div element highlighted.

enter image description here

This may explain why substring(//div[contains(text(),'Man')], 2) doesn't work. Sadly, I can't find info about this in documentation.

So, as the alternative you can use $x(path) or Document.evaluate() in Console.
For example,
$x("substring(//div[contains(text(),'Man')], 2)")
or
document.evaluate("substring(//div[contains(text(),'Man')], 2)", document)

qwermike
  • 1,446
  • 2
  • 12
  • 24
  • Thanks but neither one these returns the partial string, so they are not a solution. The result should be _naging Partner, Fort Worth Office_. The first two chars, _Ma_, should have been removed by substring(). – prevail Nov 13 '18 at 06:32
  • That's because text inside `div` is *"↵Managing Partner, Fort Worth Office↵↵"*. So, *substring* from position *2* returns *"Managing Partner, Fort Worth Office↵↵""*. – qwermike Nov 13 '18 at 07:15
  • You can eliminate leading and trailing white-spaces by `normalize-space`. So to get *"naging Partner, Fort Worth Office"* - you'll use `substring(normalize-space(//div[contains(text(),'Man')]), 3)` – qwermike Nov 13 '18 at 07:22
  • Thanks. It works so you have answered my question. I just wish I could get this to work in Node.js. The [doc.evaluate()](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate) function does not return a match. – prevail Nov 13 '18 at 23:20
  • I don't know what do you use in nodejs, but you can use *evaluate* function in [jsdom](https://www.npmjs.com/package/jsdom) or just use [package specifically for xpath](https://www.npmjs.com/package/xpath). – qwermike Nov 14 '18 at 06:22