Creating CSS selector using Xpaths
Table 1: CSS vs. Xpath
Goal
|
CSS 3
|
XPath
|
All Elements
|
*
|
//*
|
All P
Elements
|
p
|
//p
|
All Child
Elements
|
p > *
|
//p/*
|
Element By
ID
|
#foo
|
//*[@id='foo']
|
Element By
Class
|
.foo
|
//*[contains(@class,'foo')]
1
|
Element With
Attribute
|
*[title]
|
//*[@title]
|
First Child
of All P
|
p >
*:first-child
|
//p/*[0]
|
All P with
an A child
|
Not
possible
|
//p[a]
|
Next Element
|
p + *
|
//p/following-sibling::*[0]
|
Table 2: Table 1: CSS vs. Xpath
XPath
|
CSS
equiv
|
Explanation
|
//div
|
div
|
Find
elements of a particular type
|
id(‘bob’)
or //*[@id='bob'] |
#bob
|
Find
elements with a specific ID
|
//div[@id='bob']
|
div#bob
|
Find an
elements of a particular type with a specific ID
|
//*[@class='bob']
|
.bob
|
Find
elements with a specific class
|
//div[@class='bob']
|
div.bob
|
Find
elements of a particular type with a specific class
|
//div//a
|
div a
|
Find
descendant elements of a particular type
|
//div/a
|
div >
a
|
Find
direct child elements of a particular type
|
//a[@title]
|
a[title]
|
Find
elements of a particular type that have a specific attribute
|
//a[@title='bob']
|
a[title="bob"]
|
Find
elements of a particular type that have an attribute of a specific value
|
//a[contains(@title,'bob')]
|
a[title*="bob"]
|
Find
elements of a particular type that have an attribute that contains a specific
value
|
//a[starts-with(@title,'bob')]
|
a[title^="bob"]
|
Find
elements of a particular type that have an attribute that starts with a
specific value
|
Few
Examples:
xpath=//div//span/a
css=div * span > a
xpath=//div[@id="some_id"]
css=div[id=some_id]
xpath=//div[contains(@title,"title")]
css=div[@title~=title]
<div id=some_id />
css=div#some_id
xpath=//div[@class="myclass"]
css=div.myclass
<div title="some multiword title" /> while
the element like <div
title="my_title" />
can't be
detected by CSS locator from above.
Note:
Things that XPath can do those CSS locators can’t:
Get an element’s parent, eg: //div[@class='bob']/..
From the
sample above we may see analogy for XPath and CSS namely:
a) Character "/" meaning next level of DOM hierarchy corresponds to CSS operator ">".
b) Character "//" meaning any object hierarchy level under current object corresponds to CSS operator "*".
a) Character "/" meaning next level of DOM hierarchy corresponds to CSS operator ">".
b) Character "//" meaning any object hierarchy level under current object corresponds to CSS operator "*".
Sources:
thanks for shared wonderful information of giving best information.its more useful and more helpful. great doing keep sharing
ReplyDeleteBest CAT Coaching in Chennai