Skip to main content

All Locators for finding WebElements in Selenium/PlayWright

Selenium is an open source library/toolset for automating web browser interactions within a web application. 


Now these interactions can be created using Locators. These locators are used to identify webElements within a web page. These elements can vary from images, buttons, dropDowns, calendars, input fields etc. 


Now,


What are different types of locators in Selenium?


ID - A webElement having a unique ID attribute, then it can be used to identify it. 

Example - driver.findElement(By.id("depart-from")); 


NAME - A webElement having a unique NAME attribute, but in most cases multiple elements can have the same name, so it’s less reliable. 

Example - driver.findElement(By.name("signInButton")); 




LinkText : Accessing links using their exact link text, This makes it easy to create such locators, but these are flaky because they can fail when text changes for links used.

Example: driver.findElement(By.linkText("click here")).click();


Partial LinkText : Accessing links using a portion of their link text is done using the By.partialLinkText() method. 

Example: driver.findElement(By.partialLinkText("here")).click();


TagName : Using the HTML tagname directly to identify the webElement. It is easy to implement but can be challenging to find a unique tagname each time. 


Example: driver.findElement(By.tagName (“htmltagname”));


// Click on the textbox and send value  

driver.findElement(By.tagName("input")).sendKeys("JAVA");



CSS : Used to identify webElements based on different properties such as:

ID

Class

Attribute


1. CSS selector finding webElements using ID

Majorly there are 3 ways to find elements using ID in CSS selectors:-


We can use “#” notation to select the “id” attribute of an element


We can use tagName and “id” attribute of an element


We can use syntax like - <tagname>[id=’<id value>’]


Examples: 
driver.findElement(By.cssSelector("a#offers")) // Using tagName & ID
driver.findElement(By.cssSelector("#offers")); // Using only ID
driver.findElement(By.cssSelector("a[id='offers']")); // Using a fixed syntax

2. CSS Selector finding webElements using ClassName


Majorly there are 3 ways to find elements using ClassName in CSS selectors:-


We can use “.” notation to select the “class” attribute of an element


We can use tagName and “id” attribute of an element


We can use syntax like - <tagname>[class=’<class value>’]


Examples: 

driver.findElement(By.cssSelector("a.Navbar_logo")); // Using tagName & className

driver.findElement(By.cssSelector(".Navbar_logo"));; // Using only className

driver.findElement(By.cssSelector("a[class='Navbar_logo']")); // Using a fixed syntax



3. CSS Selector finding webElements using Attribute


Majorly there are 1 way to find elements using Attribute in CSS selectors:-


driver.findElement(By.cssSelector(“<tagname>[href=’<href value>’]”));


Examples: 


driver.findElement(By.cssSelector("a[href='/login']"));

Note: Other attributes like placeholder, text etc. can also be used!




XPath (XML Path Language)

It enables testers to navigate any DOM XML structure, which can be used on both HTML and XML documents


Majorly there are 2 ways to create XPath:

Absolute XPath

Relative XPath


Note 1: CSS selectors are considered to be faster to work as compared to XPath, but I didn’t find any such issues & I have primarily been using XPath selectors. 


Note 2: XPath selectors work in both forward and backward tracing of elements in DOM.



Absolute XPath : Begins from the root of the HTML document and specifies the complete path to the element. It’s not as flexible and can break if the page structure changes.


Example: html/body/form/input[3]

driver.findElement(By.xpath("//body")).sendKeys(Keys.SPACE);


Relative XPath : Starts from a specific element and navigates through the DOM hierarchy to locate the desired element. It’s much easier to customize and use. Double slash is used to create relative xpath.


Example: //form/input[3]

driver.findElement(By.xpath("//body")).sendKeys(Keys.SPACE);



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']





Understanding Xpath Creation: 


Using Text of the element to build xpath:


Syntax: //div[@class='homepage-­‐hero']//a[text()='Enroll now']


Using Contains Keyword to find the elements:


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


Using Starts-­‐With Keyword  to find the elements:


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


XPath Axes: 



Parent Keyword - used to retrieve the parent node of the current node selected

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

Example: //[@id='rt-feature']//parent::div


Preceding Sibling Keyword - will return the immediate element of the particular element

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

Example: //[@type='submit']//preceding::input


Following Sibling Keyword - will return the preceding element of the particular element

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

Example: //[@type='text']//following::input




Descendant Keyword - will return the descendant elements of the particular element. It returns all the webElements which are present with that particular selector. 

Syntax: xpath-­‐to-­‐some-­‐element//descendant::<tag>

Example: //[@id='rt-feature']//descendant::a


-x-x-


If you want to become SDET/Test Automation Engineer. then do explore courses below:


Courses:


Become a SDET and Future SDET Manager: https://topmate.io/japneet_sachdeva/778782


Crack Test Automation Interviews using JAVA: https://topmate.io/japneet_sachdeva/799592


Become Test Automation Engineer and Future Test Architect: https://topmate.io/japneet_sachdeva/510872


QA, UI and API Automation Course: https://topmate.io/japneet_sachdeva/666423


E-Books: 


Reduce your workload smartly using AI: https://topmate.io/japneet_sachdeva/764225


Learn to code in Java and crack coding interviews: https://topmate.io/japneet_sachdeva/797323


Crack QA Automation Interviews: https://topmate.io/japneet_sachdeva/772484


Attract and become a job magnet: https://topmate.io/japneet_sachdeva/730957


One on One calls: 


Career Guidance with LinkedIn and Resume Review: https://topmate.io/japneet_sachdeva/110838


1:1 Mentorship and Resume Review: https://topmate.io/japneet_sachdeva/110839


Mock Interviews for getting into SDET/Test Automation Roles: https://topmate.io/japneet_sachdeva/110841

Comments

Popular posts from this blog

Links for my courses, E-Books and lot more

Links for my E-Books:  AI & Prompt Engineering E-Book :  Link QA, Automation, API Testing & Interview Prep E-Book :  Link Complete JAVA E-Book prepared for QA Automation Engineers Interviews :  Link Strategies for How to get jobs in 2024 using AI and my resume with templates, profile optimization techniques :  Link Improve and Strategize your Personal Finance & Growth :  Link Links for my Courses:  Full Stack QA with Automation, API, DB testing, CI/CD and my E-Books for Interview Prep :  Link QA, UI and API Test Automation Course :  Link Links For my E-Books Packages:  All E-Books and CheatSheets package :  Link JAVA & QA Automation, API Testing & Interview Prep E-Books Package :  Link 1:1 Calls and Counselling Sessions Booking Links:  Career Guidance :  Link Mock Interview :  Link Looking for Motivation & Dedication? :  Link If you want to contact me with some of your queries, then u...

Performance Testing Interview Questions

 Top Performance Testing Interview Questions ----------------------------------------------------------- I mage by:  freepik How do you identify performance bottlenecks? Answer: Performance bottlenecks can be identified through various techniques, including: Performance profiling and monitoring tools. Load testing and stress testing. Analyzing system metrics like response times, CPU usage, and memory consumption. Performance counters and logs. Code reviews and analysis. What is the goal of performance tuning? Answer: The goal of performance tuning is to optimize the application’s performance by identifying and resolving performance bottlenecks. It involves making changes to the system configuration, code optimization, database tuning, and resource allocation to improve overall performance. What is a ramp-up in performance testing? Answer: A ramp-up is a gradual increase in the number of virtual users or load over a specific time period during performance testing. It helps simu...

Complete RoadMap from Manual QA To QA Automation

In this article I have provided a comprehensive guide about different technologies, frameworks and programming languages that can be used to advance your career. Now if you know or understand one technology from each domain, does not mean you should not learn something new. Grasping more knowledge will always help to create a new perspective, hence keep learning. Image by Japneet Sachdeva Version Control System (VCS) Tools: Git, SVN Why? Use: Track changes, manage source code versions, and facilitate collaboration among team members. Version Control System (VCS) CI Servers Tools: Jenkins, Travis CI, GitLab CI, GitHub Actions, CircleCI Why? Use: Automate the build, test, and deployment processes triggered by code changes in the version control repository. Build Automation Tools: Maven, Gradle (Java), npm (JavaScript), MSBuild (Microsoft) Why? Use: Compile source code, manage dependencies, and package the application or tes...

My YouTube Videos

My LinkedIn Posts