Element Locators using XPath

Expressions

 xpath=xpathExpression
   xpath=//img[@alt='The image alt text']
   xpath=//table[@id='table1']//tr[4]/td[2]
   xpath=//a[contains(@href,'#id1')]
   xpath=//a[contains(@href,'#id1')]/@class
   xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
   xpath=//input[@name='name2' and @value='yes']
   xpath=//*[text()="right"]

DOM – Javascript

 xpath=xpathExpression
 dom=document.forms['myForm'].myDropdown
 dom=document.images[56]
 dom=function foo() { return document.links[1]; }; foo();

How to find particular text in web driver method

WebDriver driver = new FirefoxDriver();
driver.get("https://localhost:8080/Login");

//Finds the xpath of element which contains UserName
WebElement strElemnt1 = driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/div[2]/p[1]/b"));

How to get Last Row in Table

//How to get Last Row in Table 
String cssLast="table[class='dataTable']>tr:first-child>td:last-child"
String cssFirst="table[class='dataTable']>tr:last-child>td:last-child"

driver.findElement(By.cssSelector(cssLast)).getText();
driver.findElement(By.cssSelector(cssFirst)).getText();

By Using XPath

//By Using XPath
WebElement lastCellInFirstRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[1]//td[last()]"));
WebElement lastCellInLastRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[last()]//td[last()]"));

How to detect custom attribute

//How to detect custom attribute 
assertTrue(selenium.isElementPresent("//*[@btn-tag-title='Sign In']"));
selenium.click("//*[@btn-tag-title='Sign In']");

assertTrue(selenium.isElementPresent("css=*[btn-tag-title='Sign In']"));
selenium.click("css=*[btn-tag-title='Sign In']");

Finding custom attribute of span where attr=”data-automation-id” and val=”SEL_ERR”

//HTML Code
<span data-automation-id="SEL_ERR">
  Error Description
</span>

//Selenium Code
driver.findElement(By.cssSelector("span[data-automation-id='SEL-ERR']"));

If Selenium cannot find it, it’ll throw an exception. Exceptions are costly. You can use .findElements instead (mentioned in 1)), which will simply return an empty list if it cannot find the element you are looking for

driver.findElements(By.cssSelector("span[data-automation-id='SEL-ERR']")).size() != 0;