Now let’s try automating this using Selenium. Here is the Java program written in Eclipse for the same:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XPathexample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Your-Chrome-Driver-Path"); // Provide the path to your chrome driver. Make sure your chrome driver version is updated.
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/account/create");
driver.findElement(By.xpath("//input[@id='usernamereg-firstName']")).sendKeys("Your-Name"); // Will send values to First Name tab
}
}
Similarly, fill in all the details and find elements by XPath in Selenium.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XPathexample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Your-Chrome-Driver-Path"); // Provide the path to your chrome driver. Make sure your chrome driver version is updated.
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/account/create");
driver.findElement(By.xpath("//input[@id='usernamereg-firstName']")).sendKeys("Your-Name"); // Will send values to First Name tab
driver.findElement(By.xpath("//input[@id='usernamereg-lastName']")).sendKeys("Your-Last_name"); //xpath for last name box
driver.findElement(By.xpath("//input[@id='usernamereg-yid']")).sendKeys("email@yahoo.com"); //xpath for email box
driver.findElement(By.xpath("//input[@id='usernamereg-phone']")).sendKeys("123456789"); //xpath for phone number box
driver.findElement(By.xpath("//select[@id='usernamereg-month']")).click(); //xpath for usermonth box
driver.findElement(By.xpath("//input[@id='usernamereg-day']")).sendKeys("01"); //xpath for userday box
driver.findElement(By.xpath("//input[@id='usernamereg-year']")).sendKeys("1999"); // xpath for user year
driver.findElement(By.xpath("//button[@id='reg-submit-button']")).click(); // xpath for submit button
}
}
One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate. You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than id and name.,There are various strategies to locate elements in a page. You can use the most appropriate one for your case. Selenium provides the following method to locate elements in a page:,The ‘By’ class is used to specify which attribute is used to locate elements on a page. These are the various ways the attributes are used to locate elements on a page:,Use this when you want to locate an element by class name. With this strategy, the first element with the matching class name attribute will be returned. If no element has a matching class name attribute, a NoSuchElementException will be raised.
from selenium.webdriver.common.by
import By
driver.find_element(By.XPATH, '//button[text()="Some text"]')
driver.find_elements(By.XPATH, '//button')
ID = "id"
NAME = "name"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"
find_element(By.ID, "id")
find_element(By.NAME, "name")
find_element(By.XPATH, "xpath")
find_element(By.LINK_TEXT, "link text")
find_element(By.PARTIAL_LINK_TEXT, "partial link text")
find_element(By.TAG_NAME, "tag name")
find_element(By.CLASS_NAME, "class name")
find_element(By.CSS_SELECTOR, "css selector")
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
</form>
</body>
</html>
login_form = driver.find_element(By.ID, 'loginForm')
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
</html>
Note: we use @ sign for attributes, functions do not need @ sign We can also match element(s) which have text in them with below XPath, There will be situations, where you may not able to use any HTML property other than text present in the element text() function helps us to find the element based on the text present in the element, text() function is case sensitive,We have to use parenthesis to make an xpath into group XPath after it indexes the XPath Store below HTML code into HTML file :, We can use index type XPath with webdriver when we have more matches under one parent, the index might not work if there are more parent Store below HTML in the local system and open it with chrome
We can write Xpath based on Tagname, which is very simple.
Syntax for Xpath with Tagname : //tagName
<html>
<body>
<div id="pancakes">
<button type="button">Blueberry</button><br><br>
</div>
</body>
</html>
We may not see unique elements in the webpage, other than on login page.
Please save the below HTML file as composite-xpath.html on your local machine
<html>
<body>
<div id="pancakes">
<button type="button">Blueberry</button><br>
<>
<button type="button">Banana</button><br><br>
<button type="button">Strawberry</button><br><br>
</div>
</body>
</html>
Open above HTML file in chrome, and press F12 or right-click on the element and choose Inspect Elementor Press Ctrl+Shift+I
It may look like the below image once you open the chrome developer tool
Press Ctrl+F to verify Xpath, and write the XPath based on the XPath syntax.
Xpath based on the Tagname : //button
When you try the XPath with tagname it shows three matches, so we cannot proceed as we want to find only one match. We must write an XPath expression which should have only one match. When we have a matching element only under one parent(this case), we should add an index to the XPath
Syntax
for Xpath with Index: //tagName[index]
We can use index type XPath with webdriver when we have more matches under one parent, the index might not work if there are more parent
Store below HTML in the local system and open it with chrome
We can use index type xpath with webdriver when we have more matches under one parent, index might not work if there are more parent
Store below html in local system and open it with chrome
<html>
<body>
<div id="pancakes">
<button type="button">Blueberry</button><br><br>
<button type="button" name='banana'>Banana</button><br><br>
<button type="button">Strawberry</button><br><br>
</div>
<div id="pancakes">
<button type="button">Apple</button><br><br>
<button type="button">Orange</button><br><br>
<button type="button">Grape</button><br><br>
</div>
</body>
</html>
Let's try to write xpath for Banana button, Xpath based on index is //button[2] but it has two matches 1. Banana, 2.Orange.
With index we may not be able to solve this issue.
Let's consider other properties of the html element, banana has attribute name, Now we have to form the xpath based on the attribute.
Xpath with Attribute ://tagName[@attribute='attribute value']
Xpath based on the Attribute is : //button[@name='banana'] , this xpath shows only one match which is Banana button
You can add n number attributes in one xpath itself
Xpath with multiple Attributes://tagName[@attrib='attrib value'][@attrib2='attrib2 value']...
Can I use index along with attribute: yes , you can use, but index will be usefull only when matches are under single parent
Xpath with Attribute and Index://tagName[@attribute='attribute value'][index]
Let's try to write XPath for Banana button, Xpath based on an index is //button[2] but it has two matches 1. Banana, 2.Orange.
With an index, we may not be able to solve this issue.
Let's consider other properties of the HTML element, banana has attribute name, Now we have to form the XPath based on the attribute.
Xpath with Attribute: //tagName[@attribute='attribute value']
Xpath based on the Attribute is : //button[@name='banana'], this XPath shows only one match which is Banana button
You can add n number attributes in one XPath itself
Xpath with multiple Attributes: //tagName[@attrib='attrib value'][@attrib2='attrib2 value']...
We cannot expect an HTML element to have different or uniques properties all the time, sometimes there is a chance that every element may have the same kind of attributes, In those cases, we cannot use Xpath with Attribute in selenium webdriver
To handle such kind of cases we may need to take help of the parent element to find our actual element
Store the below code in HTML file and open it in chrome
<html>
<body>
<div id="berry">
<button type="button">Blueberry</button><br><br>
<button type="button">Banana</button><br><br>
<button type="button">Strawberry</button><br><br>
</div>
<div id="fruit">
<button type="button">Apple</button><br><br>
<button type="button">Orange</button><br><br>
<button type="button">Grape</button><br><br>
</div>
</body>
</html>
Sometimes we may have to handle the elements with XPath index but the index may give more than one match, which are under different parents, in these situations index might not help you. We may have to use Group index in this kind of scenarios
Group index puts all matches into a list and gives indexes them. So here we will not have any duplicates matches
Syntax: ( //tagName)[index]
We have to use parenthesis to make an xpath into group XPath after it indexes the XPath
Store below HTML code into HTML file :
<html>
<body>
<div id="fruit"><br><br><br>
<button type="button">Blueberry</button><br><br>
<button type="button">Banana</button><br><br>
<button type="button">Strawberry</button><br><br>
</div>
<div id="fruit">
<button type="button">Apple</button><br><br>
<button type="button">Orange</button><br><br>
<button type="button">Grape</button><br><br>
</div>
</body>
</html>
There will be situations, where you may not able to use any HTML property other than text present in the element
text() function helps us to find the element based on the text present in the element, text() function is case sensitive
<button type="button">Blueberry</button><br><br>
In the above code, the text is Blueberry, and we can write XPath using text() like below
xpath with text: //button[text()='Bluberry']
Note: we use @ sign for attributes, functions do not need @ sign
We can also match element(s) which have text in them with below XPath
xpath with text: //button[text()]
: //button/text()
Another useful method to locate an element is using an XPath expression. We use XPath when a proper id or name attribute is not present in the code to access that element.,XPath locators can also use attributes other than id and name for locating the element.,Here is the code snippet that demonstrates the use of <find_element_by_name> method. Below code opens Google in the browser and performs a text search.,It is not possible to interact with the web page if the test script is not able to find the web elements. Selenium Webdriver provides the following techniques for locating the web elements.
Here is the code snippet that demonstrates the use of <find_element_by_name> method. Below code opens Google in the browser and performs a text search.
from selenium
import webdriver
import time
from selenium.webdriver.common.keys
import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
driver.maximize_window()
time.sleep(5)
inputElement = driver.find_element_by_name("q")
inputElement.send_keys("Techbeamers")
inputElement.submit()
time.sleep(20)
driver.close()
Here is the code snippet that demonstrates the use of the <find_element_by_id> method. Below code opens Google in the browser and performs a text search.
from selenium
import webdriver
import time
from selenium.webdriver.common.keys
import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
driver.maximize_window()
time.sleep(5)
inputElement = driver.find_element_by_id("lst-ib")
inputElement.send_keys("Techbeamers")
inputElement.submit()
time.sleep(20)
driver.close()
Here is the code snippet that demonstrates the use of <find_element_by_link_text> method. Below code opens Google in the browser and performs a text search. After that, it opens a Hyperlink with link text as “Python Tutorial.”
from selenium
import webdriver
import time
from selenium.webdriver.common.keys
import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
driver.maximize_window()
time.sleep(5)
inputElement = driver.find_element_by_name("q")
inputElement.send_keys("Techbeamers")
inputElement.submit()
time.sleep(5)
elem = driver.find_element_by_link_text("Python Tutorial")
elem.click()
time.sleep(20)
driver.close()
To understand the Absolute and Relative path, let’s take the following HTML code for user SignUp.
<html>
<body>
<form id="signUpForm">
<input name="emailId/mobileNo" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="SignUp" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
<html>
Here are the XPaths that will help Selenium Webdriver to locate the form element.
form_element = driver.find_element_by_xpath("/html/body/form[1]")