How to stop insert implicit tags when using `Copy

2019-07-28 17:18发布

问题:

I use Copy Xpath function in Chrome developer tools for nokogiri xpath parser.

But like this question, Chrome and Firefox's Developer tools insert tags like <tbody> implicitly.

Is there a way to get "real" xpath that I can use for nokogiri xpath parser?

回答1:

When you extract XPath from a browser, you do that form the actual DOM, where it is too late to know whether the <tbody> element was there or whether it was added implicitly.

You can replace all instances of /tbody/ with // so you don't care which case is it:

xpath = '//html/body/p/table/tbody/tr/td[2]/table/tbody/tr[2]'

xpath.gsub('/tbody/', '//')
# => "//html/body/p/table//tr/td[2]/table//tr[2]"