Question

how can i convert xpath like

/html/body/div[3]/ul/li[1]/a[5]

html > body > div[3] > ul > li[1] > a[5]

i believe, index is not supported with CSS3 selectors....so how to deal with this ?

Was it helpful?

Solution

If you find that Sizzle/jQuery can't apply your CSS3 selector it might be better to use the XPath plugin which was part of the original release of jQuery (and then removed since few people actually used it).

XPath implementations in browsers tends to be much faster than the CSS engines. Also having JS parse & convert an XPath expression into CSS3 then having jQuery munge that into something the browser can implement (generally CSS2.1 selectors with a bit of JS assistance) is going to be much slower than executing the XPath directly in the browser.

Not only that, but there are things that XPath can do that CSS can't. For example:
//h3[class="blog-title"]/../../div[class="blog-entry"]//input[fn:floor(value) > 3]
which isn't overly complex for XPath to execute, but impossible for CSS alone - moving back up the DOM and executing a function as part of the expression can't (to my knowledge) be done yet, even in CSS3.

OTHER TIPS

Selenium 1′s CSS locator engine moved from CSSQuery to Sizzle, jQuery’s CSS selector library. So you can convert

div[3]/ul/li[1]/a[5] 

to

css=div:nth(3)>ul>li:nth(1)>a:nth(5)

and

//h3[class="blog-title"]/../../div[class="blog-entry"]//input[@value=3] 

can be converted to

css=h3.blog-title:parent(div.blog-entry) input[value=3]

however //input[@value>3] cannot be possible or be tricky For more info visit: https://github.com/jquery/sizzle/wiki/Sizzle-Home

the xpath implementation in IE is very, very slow. even terrifying slow in IE6 thats why most tend to use CSS selectors based on regex etc. like sizzle or the newest is qwery. for a index select you use in CSS the selector :nth-child(n)

a[5] = :nth-child(5)

i cant remember if it starts with 0 or 1 so it could also be 4.

also if you have different types of children within the parent you are selecting in, you can use :nth-of-type() which selects only the given type. in your case:

a:nth-of-type(5)

Searched for quite a bit and finally found these 2 libraries. Hope it helps someone as lost as me:

  1. James Padolsey's CSS2XPATH that was used by YQL HTML at one point of time
  2. css2xpath - A generic CSS to XPath transformer

As this is quite a niche area, I welcome the community to make edits to this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top