Deal with Web Elements and Locators to automate by selenium

Refer Youtube video for quick reference – Indetify the Web Elements and Locators – Part 1Indetify the Web Elements and Locators – Part 2

What is Web Element

  • HTML documents are made up by HTML elements. HTML elements are written with a start tag, with an end tag, with the content in between: <tagname> content </tagname>
  • WebElement represents an HTML element.

<html><body>

<strong>First name:</strong>            <input type=”text” name=”firstname”>

<strong>Last name:</strong><input type=”text” name=”lastname”>

</body></html>

  • So, here First Name and Last Name Text box are Web Elements of Web Page.In selenium we can find the web element by their html locator type.
  • Locators are the HTML properties and it address that identifies a web element uniquely within the web page
  • Here we can find the first and last name by locator type “name” and their value “firstname” and “lastname”

Most common web elements are present on the Web Page

  • Text box
  • Button
  • Link Text
  • Check box
  • Radio button
  • Drop down box
  • List box
  • Web Table(Html table)
  • Frame
  • File
  • Image, Image Link, Image button

Most common locator type

Locator

Locating elements in WebDriver is identify by using the findElement(By.locator())The findElement methods take a locator or query object called ‘By’.

1. Text box

Find “Text box” element by locator type ‘id, name’

  • Step 1: Launch the web browser (Firefox) and navigate to – https://accounts.google.com/
  • Step 2: Open firebug (either by pressing F12 or via tools).
  • Step 3: Click on the inspect icon on text box to identify the web element.
  • Selenium code – driver.findElement(By.id(“Email”))
    • Finding “Text box” element by locator ‘name’

    Selenium code – driver.findElement(By.name(“Email”))

  • Most common operations perform on Text box (Edit Box)
    • Clear – driver.findElement(By.id(“Email”)).clear()
    • Enter Text value – driver.findElement(By.id(“Email”)).sendKeys(“Test”)
    • Element display or not – Boolean status = findElement(By.id(“Email”)).isdisplayed()

Practical Demo– Test ‘Text box’

Test Scenario:  Identify the Gmail Email and Password text box and Enter Value in it           Steps:

  1. Open Gmail Url (gmail.com) in the Browser
  2. Check that Email text box display on the page
  3. Check that Email text box is editable (Enable)
  4. Clear the text box if any text present in the text box
  5. Enter demo@test.com value in the email text box

Script :

System.setProperty(“webdriver.chrome.driver”,”C:\\chromedriver_win32\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.get(“https://accounts.google.com&#8221;); // Step 1 – Open gmail in the chrome Browser
WebElement LoginText = driver.findElement(By.name(“Email”)); // find the webelement of Email text box
boolean chkdisplay = LoginText.isDisplayed(); // Step 2 – Check Email field is display on page or not
if (chkdisplay == true)
{
boolean chkenable = LoginText.isEnabled(); // Step 3 – Check email field is editable or npt
if (chkenable == true)
{
System.out.println(“Email Text box is Present on the page”);
LoginText.sendKeys(“demo@test.com”);
Thread.sleep(2000);
}
else
{
System.out.println(“Email Text box is not editable”);
}
System.out.println(“Text box Test Passed”);
}
else
{
System.out.println(“Email Text box is not present on the page”);
}
driver.close();
}

2. Button

Find “Button” element by locator type ‘id or class or name’

Selenium code

  • findElement(By.id(“submit”))
  • findElement(By.classname(“btn btn-info”))
  • findElement(By.name(“submit”))

Most common operations perform on Text box (Edit Box)

  • Submit – driver.findElement(By.id(“Email”)).submit() // This method works well/better than the click()

3. Link Text

Find “Link Text” element

  • Step 1: Launch the web browser (Firefox) and navigate to – http://toolsqa.com/automation-practice-form/
  • Step 2: Open firebug
  • Step 3: Click on the inspect icon on text present within the <a> </a> tags and identify the web element.

Selenium code

  • findElement(By. linkText(“Link Text name”)
  • Most common operations perform on Link Text
  • Click – findElement(By. linkText(“Link name”)).click()

Demo – Test ‘Button’, ‘Link Text’

Test Scenario:  Click on Submit button

Steps:

  1. Launch new Browser
  2. Open URL http://toolsqa.wpengine.com/automation-practice-form/
  3. Identify Submit button with ‘tagName’, convert it in to string and print it on the console
  4. Click on submit button
  5. Click on the Link “Link Test”

Script:

WebDriver driver = new ChromeDriver();
driver.get(“http://toolsqa.com/automation-practice-form/&#8221;); // Step 1 – Open gmail in the chrome Browser
//Find sumit button and click
String sClass = driver.findElements(By.tagName(“button”)).toString();
System.out.println(sClass);
WebElement button = driver.findElement(By.id(“submit”));
button.submit();

//button.submit(); // Use submit method to click
//Find Link by name and click
Thread.sleep(2000);
WebElement linkText = driver.findElement(By.linkText(“Link Test”));
linkText.click();
System.out.println(“Button and Link Test Passed”);
driver.close();

4. Check Box/Radio button

  • Find “Check Box” element by locator type ‘id or name’
  • Step 1: Launch the web browser (Firefox) and navigate to – http://toolsqa.com/automation-practice-form/
  • Step 2: Open firebug
  • Step 3: Click on the inspect icon on single or group of Radio Buttons/Check Boxes and identify the web element.

Selenium code

  • WebElement radioBtn = driver.findElement(By.id(“toolsqa”));
  • List  oRadioButton = driver.findElements(By.name(“toolsqa”));
  • WebElement oCheck Box=driver.findElement(By.cssSelector(“input[value=’Selenium IDE’]”));

Name is always same for the same group of Radio Buttons/Check Boxes but their Values are different

Most common operations perform on Radio Buttons/Check Boxes

  • Click – driver.findElement(By.id(“toolsqa”)).get(1).click()
  • Is Selected – booleanbValue = findElement(By.id(“toolsqa”)).get(2).isSelected()
  • Fine check box text – StringsValue = findElement(By.id(“toolsqa”)).get(1). getAttribute(“value”)

Demo – Test ‘Radio and check box’

Test Scenario : Select Year of experience radio button one by one

Steps:

  1. Open URL http://toolsqa.wpengine.com/automation-practice-form/
  2. Identify the Gender radio buttons and Select the ‘Female’ radio button by Value
  3. Identify Year of Experience radio buttons by name and select each radio button one by one
  4. Select Year of Experience radio button one by one
  5. Identify the Profession check box and Select the ‘Automation Tester’ check box  by value

Script:

WebDriver driver = new ChromeDriver();
// Step 1: Open Test URL
driver.get(“http://toolsqa.com/automation-practice-form&#8221;);

// Step 2: Identify the Gender radio buttons and Select the ‘Female’ radio button by Value
List<WebElement> rdBtn_Sex = driver.findElements(By.name(“sex”)); //
int size = rdBtn_Sex.size();
System.out.println(“Total no of radio button :”+size);
for (int i=0; i< size; i++)
{
String sValue = rdBtn_Sex.get(i).getAttribute(“value”); // Step 3 – 3. Select the Radio button (female) by Value ‘Female’
System.out.println(“Radio button Name “+sValue);
if (sValue.equalsIgnoreCase(“Female”))
{
rdBtn_Sex.get(i).click();

}
}
// Step 3: Identify Year of Experience radio buttons by name and select each radio button one by one
List<WebElement> rdBtn_exp = driver.findElements(By.name(“exp”));
System.out.println(“Total no of Year radio button :”+rdBtn_exp.size());
for (WebElement wb : rdBtn_exp)
{
wb.click(); // Step 5. Select Year of Experience radio button one by one
Thread.sleep(2000);
}
// alternative for loop
// for(int i =0; i < rdBtn_exp.size() ; i++ )
// {
// rdBtn_exp.get(i).click();
// Thread.sleep(2000);
// }

//Select check box profession ‘Automation Tester’
List<WebElement> chkBox_Prof = driver.findElements(By.name(“profession”));
for (WebElement wbprof : chkBox_Prof)
{
System.out.println(“Profession name “+wbprof.getAttribute(“value”));
if (wbprof.getAttribute(“value”).equalsIgnoreCase(“Automation Tester”)){
System.out.println(“Profession name “+wbprof.getAttribute(“value”));
wbprof.click();
Thread.sleep(2000);
}

}

driver.close();

5. Drop down box

  • Find “Button” element by locator type ‘id, name, Css, Xpath’
  • Step 1: Launch the web browser (Firefox) and navigate to – http://toolsqa.com/automation-practice-form/
  • Step 2: Open firebug
  • Step 3: Click on the inspect icon on drop down box and identify the web element.

Selenium code

  • WebElement element = driver.findElement(By.id(“Country”));
  • Select oSelect = new Select(element);

OR

  • Select oSelect = new Select(driver.findElement(By.id(“Country”)));

Most common operations perform on Radio Buttons/Check Boxes

  • Select by Visible Text – selectByVisibleText(“text”)
  • Select by Index – selectByIndex(4)
  • Select by Value – oSelect.selectByValue(“2016”)
  • Get all option – List<WebElement>elementCount=oSelect.getOptions()
  • Deselect All – deselectAll()
  • Deselect by Index – deselectByIndex(1)
  • Deselect by Value – oSelect.deselectByValue(“string”)
  • Deselect by Text – oSelect.deselectByVisibleText(String arg0)

Demo – Drop down Box/List

  1. Launch new Browser
  2. Open “http://toolsqa.wpengine.com/automation-practice-form/”
  3. Select ‘Continents’ Drop down ( Use Id to identify the element )
  4. Select option ‘Europe’ (Use selectByVisibleText)
  5. Select option ‘Africa’ now (Use selectByIdex)
  6. Print all the options for the selected drop down and select one option of your choice
  7. Close the browser

Script

// Step 1 – Launch Browser
WebDriver driver = new ChromeDriver();
// Step 2 – Open Test URL
driver.get(“http://toolsqa.com/automation-practice-form&#8221;);
// Step 3: Select ‘Continents’ Drop down ( Use Id to identify the element )
Select oSelect = new Select(driver.findElement(By.id(“continents”)));
// Step 4:) Select option ‘Europe’ (Use selectByIndex)
oSelect.selectByVisibleText(“Europe”);
Thread.sleep(2000);

// Step 5: Select option ‘Africa’ now (Use selectByVisibleText)
oSelect.selectByIndex(2);
Thread.sleep(2000);

// Step 6: Print all the options for the selected drop down and select one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();

// Setting up the loop to print all the options
for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
}
// Step 7: Kill driver
driver.quit();

6. Web Table

Table is a kind of HTML data which is displayed with the help of <table> tag in conjunction with the <tr> row and <td> column tags.

  • Find “Web Table” by locator type ‘id, name, Xpath’ and find Row and Column by tagName

Demo

  1. Open URL “http://toolsqa.wpengine.com/automation-practice-table/”
  2. Find total no of rows
  3. Find total no of columns
  4. Fetch the Row Header and Column Header and print each cell data

// Step 1: Open Test URL
driver.get(“http://toolsqa.wpengine.com/automation-practice-table&#8221;);

// Step 2: Find total number of rows having effective data
WebElement tbl_rows = driver.findElement(By.xpath(“.//*[@id=’content’]/table/tbody”));
List<WebElement> rows = tbl_rows.findElements(By.tagName(“tr”));
System.out.println(“Total No of Rows :”+rows.size());

//Step 3: Find total number of columns
WebElement tbl_cols = driver.findElement(By.xpath(“.//*[@id=’content’]/table/thead/tr”));
List<WebElement> cols = tbl_cols.findElements(By.tagName(“th”));
System.out.println(“Total No of Columns :”+cols.size());
System.out.println(“Total No of Cells :”+ cols.size() * rows.size());

// Step 4: Fetch the Row Header and Column Header and print each cell data
for (int i=1;i<=rows.size();i++){
String tbl_header = driver.findElement(By.xpath(“.//*[@id=’content’]/table/tbody/tr[” + i + “]/th”)).getText();
System.out.println(“Item ” +i +” : “+tbl_header);
for (int j=1;j<cols.size()-1;j++){
String tbl_title = driver.findElement(By.xpath(“.//*[@id=’content’]/table/thead/tr/th[” + (j+1) +”]”)).getText();
String sColumnValue= driver.findElement(By.xpath(“.//*[@id=’content’]/table/tbody/tr[” + i + “]/td[“+ j +”]”)).getText();
System.out.println(tbl_title +”:”+ sColumnValue);
}
}

driver.close();

XPath 

Difference between single ‘/’ or double ‘//’

Single slash ‘/’ anywhere in xpath signifies to look for the element immediately inside the parent element.

Double slash ‘//’ signifies to look for any child or nested-child element inside the parent element.

Syntax:

//tag[@attribute=’value’]

Relative xpath using single ‘/’ for Login link

//div[@id=’navbar’]/div/div/div/ul/li[2]/a

Relative xpath using double ‘//’ for Login link.

//div[@id=’navbar’]//ul/li[2]/a

Don’t use “*”, always use the tag name.

Using Text of the element to build xpath

Finding Login link:

//div[@class=’homepage-hero’]//a[text()=’Enroll now’]

Using Contains to find the elements:

Syntax: //tag[contains(attribute, ‘value’)]

Finding Login link:

//div[@id=’navbar’]//a[contains(text(),’Login’)]

//div[@id=’navbar’]//a[contains(@class,’navbar-link’) and contains(@href,’sign_in’)]

Using Starts-With to find the elements:

Syntax: //tag[starts-with(attribute, ‘value’)]

Finding Login link:

//div[@id=’navbar’]//a[starts-with(@class,’navbar-link’)]

Parent

Syntax: xpath-to-some-element//parent::<tag>

 Preceding Sibling

Syntax: xpath-to-some-element//preceding-sibling::<tag>

Following Sibling

Syntax: xpath-to-some-element//following-sibling::<tag>

Exercise:

Find the price of the course “Python Programming Language”

Solution:

//table[@id=’product’]//td[text()=’Python Programming Language’]//following-sibling::td

Find Author of the book “The Green Mile”

Solution:

//div[@id=’gridbox’]//a[text()=’The Green Mile’]//parent::td//following-sibling::td[1]

Advertisements

About samp79

Professional Automation Tester
This entry was posted in Selenium, Test Automation. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s