SlideShare une entreprise Scribd logo
1  sur  26
Element Locators
Ilan Malyanker
Thursday, April 3rd, 2014
Connection Before Content
creates meaningful, real time
customer connections that help
businesses increase conversions and
improve consumer experience.
LivePerson is hiring- peoplejobs@liveperson.com
Ilan Malyanker Works in LP for 3 years.
8 years as an automation engineer.
Blog- http://software-automation-development.blogspot.com
mail- ilanm@liveperson.com / malyankeri@yahoo.com
Purpose & Motivation
• Identify elements to simulate operations
• Identify elements to verify their status
• Help create robust testing framework
• Share knowledge
• Expose new options for automation
developers
Terms & Code Alignment - Demo
• HTML terms in WebDriver context
• WebDriver basic usage
• Think of WebDriver as a browser instance
• WebElement- as any seen object on the page
“By” class
• Selenium WebDriver provides By class
to support various locator strategies
• Find methods take a locator or query
object as an instance of By class as an
argument
Locating Elements Using
• Id
• Links
• Tag names
• Css Selectors
• Xpath
• JQuery
• Text
Browser Tools For Element Inspection
• Firefox - „Firebug‟ add-on (right click →
„Inspect Element‟ / F12).
„FirePath‟ – Optimizing CSS & XPath
• Chrome - Built-in page analyzing feature
(right click → „Inspect Element‟ / F12)
• IE - Developers tool („Tools‟ → „Developers
Tools‟ / F12). There‟s also FireBug for IE.
• Console – Immediate diagnose & execution tool.
Available on all tools
Languages
• Java: driver.findElement(By.id(<element ID>))
driver.findElement(By.linkText(<linktext>))
• C#: driver.FindElement(By.Id(<elementID>))
driver.FindElement(By.LinkText(<linktext >))
• Python: driver.find_element_by_id(<elementID>)
driver.find_element_by_link_text(<linktext >)
• Ruby: driver.find_element(:id,<elementID>)
driver.find_element(:link_text,< linktext >)
0 matches: throws exception (org.openqa.selenium.NoSuchElementException)
1 match: returns list of 1 WebElement instance
2+ matches: returns only first appearance in DOM
1 match: returns WebElement instance
0 matches: returns an empty list
2+ matches: returns list with all matching instances
FindElement vs. FindElements
findElement()
findElements()
Id
driver.findElement(By.id(“<some_id>"));
• Seems like the ideal solution
• Id‟s don‟t always exist
• Their uniqueness is not enforced
• What about dynamic elements?
• Might be used for other future purposes
• Code injected from different sources (potential override)
• Against web developers best practices
Links
Find elements by the text displayed on
the link
driver.findElement(By.linkText(“<link_text>"));
driver.findElement(By.partialLinkText(“<link_partial_text>"))
Tag Names
Find web elements based on their HTML
tags
< class="form-inline">
< class="editable-controls">
<input class="editable-has-buttons" type="text">
<span class="editable-buttons">
<button class="btn btn-primary" type="submit">
<button class="btn btn-danger">
</span>
</div>
</form>
driver.findElement(By.tagName("input"));
*See that your tag is unique
CSS Selectors (1)
• Cascading Style Sheets- language used for
describing the presentation semantics of a document
written in a markup language such as HTML or XML.
• Browsers implement CSS parsing engines for
formatting or styling the pages using CSS syntax.
Absolute path:
driver.findElement(By.cssSelector(“html>body>div>p>input"));
Relative path:
driver.findElement(By.cssSelector(“input")) *the first instance found
CSS Selectors (2)
Regular attribute:
tag with attribute value:
driver.findElement(By.cssSelector(“button[name=„cancel‟]"));
Special attributes:
id:
driver.findElement(By.cssSelector(“#save"));
tag & id:
driver.findElement(By.cssSelector(“button#save"));
class attribute:
driver.findElement(By.cssSelector(“.yoyo"));
tag & class attribute:
driver.findElement(By.cssSelector(“input.username"));
CSS Selectors (3)
tag with attribute value:
driver.findElement(By.cssSelector(“img[alt=„kuku‟]"));
tag which has attribute:
driver.findElement(By.cssSelector(“img[alt]"));
tag which doesn‟t have attribute:
driver.findElement(By.cssSelector(“img:not([alt])"));
CSS Selectors, advanced (last css slide)
The first child of a tag with id:
driver.findElement(By.cssSelector(“div#students:first-child"));
The n-th child of a tag with id :
driver.findElement(By.cssSelector(“form#loginForm:nth-child(3)"));
Second descendent of div with id :
driver.findElement(By.cssSelector(“div#ilan>p+*+p"));
(first) tag which is enabled:
driver.findElement(By.cssSelector(“button:enabled"));
Xpath (1)
• Xpath is a query language for selecting nodes from an
XML document.
• Xpath is based on a tree representation of the XML
document and provides the ability to navigate around
the tree.
Absolute path:
driver.findElement(By.xpath(“html/body/div/p/input"));
Relative path:
driver.findElement(By.xpath(“//input"))
Xpath (2)
Tag with attribute value:
driver.findElement(By.xpath(“//input[@id=„username‟]"));
Any tag with id:
driver.findElement(By.xpath(“//*[@id=„myId']"));
Operator „and‟:
driver.findElement(By.xpath(“//input[@type='submit'][@value='Login']”));
driver.findElement(By.xpath(“//input[@type='submit„ and @value='Login']”));
Opertor or:
driver.findElement(By.xpath(“//input[@type='stam„ or @class=„LP']"));
Xpath (3)
Attribute which starts with
driver.findElement(By.xpath(“//input[starts-with(@class,„tbl_')]"));
*there‟s also- ends-with()
Attribute contains text:
driver.findElement(By.xpath(“//input[contains(@id,'userName')]"));
Match value to any attribute:
driver.findElement(By.xpath("//input[@*='username']"));
Xpath (4)
Ancestor, descendant, following, following-sibling, preceding, preceding-sibling
driver.findElement(By.xpath(“//td[text()='Product 1']/ancestor::table"));
element.findElement(By.xpath(“/table/descendant::td/input"));
*can only be applied from another WebElement
Use parent to get to same-hierarchy object:
driver.findElement(By.xpath("//div/input[@class=„kuku‟]/../button"));
Text – CSS Selectors
See if element‟s attribute contains specified text
driver.findElement(By.cssSelector(“div[id*=„my_id„]"));
(Also- ^ starts with, $ ends with)
See if element contains specified text
driver.findElement(By.cssSelector(“input:contains(„Some Text')"));
*deprecated from CSS3 specification
innerText attribute
driver.findElement(By.cssSelector("td[innerText=„Some Text']"));
*Doesn‟t work in FireFox
textContent:
driver.findElement(By.cssSelector("td[textContent=„text']"));
*For FireFox
Text – XPath
Locate element by matching exact text value
driver.findElement(By.xpath(“//td/span[text()=„Some Text‟]"));
OR
driver.findElement(By.xpath("//td/span[.=„Some Text‟]"));
See if Element contains specified text
driver.findElement(By.xpath("//td[contains(text(),„Some Text')]"));
What‟s better, xpath or css selectors?
• CSS Selectors method is faster
• Browsers themselves use css selectors
• Latest browsers optimize the use of css
Selectors
• Xpath- common language for xml/html parsing
• Xpath is a two-way search mechanism
(up&down the DOM tree)
• Xpath handles text recognition better
JavaScript Executor for JS & JQuery
JavaScript syntax as a Java String:
String script = "return document.getElementById(„some-id');";
OR
Jquery syntax as a Java String:
String script = "return jQuery('#some-id').get(0);";
JavascriptExecutor executor = (JavascriptExecutor)driver;
WebElement element = (WebElement)executor.executeScript(script);
• Opens a world of client side manipulations
• jQuery() method uses- css selectors
i. jQuery lib should be loaded on the page
ii. Same executor runs both types of scripts
iii. jQuery returns a collection, hence extract the first
instance
iv. The “$” – sign could also represent jQuery namespace
Tips & Best Practices
• Locators location
• Use Enums
• Know all your working tools
• Element Detection & Highlighting
• Expose locators and not just the methods
• Work close to client developers (4 non agile developers)
• Optimize your locators !!
i Maximum focus
ii Minimum dependencies
Visit my blog - software-automation-development.blogspot.com

Contenu connexe

Plus de LivePerson

Measure() or die()
Measure() or die() Measure() or die()
Measure() or die() LivePerson
 
Resilience from Theory to Practice
Resilience from Theory to PracticeResilience from Theory to Practice
Resilience from Theory to PracticeLivePerson
 
System Revolution- How We Did It
System Revolution- How We Did It System Revolution- How We Did It
System Revolution- How We Did It LivePerson
 
Liveperson DLD 2015
Liveperson DLD 2015 Liveperson DLD 2015
Liveperson DLD 2015 LivePerson
 
Http 2: Should I care?
Http 2: Should I care?Http 2: Should I care?
Http 2: Should I care?LivePerson
 
Mobile app real-time content modifications using websockets
Mobile app real-time content modifications using websocketsMobile app real-time content modifications using websockets
Mobile app real-time content modifications using websocketsLivePerson
 
Mobile SDK: Considerations & Best Practices
Mobile SDK: Considerations & Best Practices Mobile SDK: Considerations & Best Practices
Mobile SDK: Considerations & Best Practices LivePerson
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Apache Avro in LivePerson [Hebrew]
Apache Avro in LivePerson [Hebrew]Apache Avro in LivePerson [Hebrew]
Apache Avro in LivePerson [Hebrew]LivePerson
 
Apache Avro and Messaging at Scale in LivePerson
Apache Avro and Messaging at Scale in LivePersonApache Avro and Messaging at Scale in LivePerson
Apache Avro and Messaging at Scale in LivePersonLivePerson
 
Data compression in Modern Application
Data compression in Modern ApplicationData compression in Modern Application
Data compression in Modern ApplicationLivePerson
 
Support Office Hour Webinar - LivePerson API
Support Office Hour Webinar - LivePerson API Support Office Hour Webinar - LivePerson API
Support Office Hour Webinar - LivePerson API LivePerson
 
SIP - Introduction to SIP Protocol
SIP - Introduction to SIP ProtocolSIP - Introduction to SIP Protocol
SIP - Introduction to SIP ProtocolLivePerson
 
Scalding: Reaching Efficient MapReduce
Scalding: Reaching Efficient MapReduceScalding: Reaching Efficient MapReduce
Scalding: Reaching Efficient MapReduceLivePerson
 
Building Enterprise Level End-To-End Monitor System with Open Source Solution...
Building Enterprise Level End-To-End Monitor System with Open Source Solution...Building Enterprise Level End-To-End Monitor System with Open Source Solution...
Building Enterprise Level End-To-End Monitor System with Open Source Solution...LivePerson
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data ScienceLivePerson
 
From a Kafkaesque Story to The Promised Land at LivePerson
From a Kafkaesque Story to The Promised Land at LivePersonFrom a Kafkaesque Story to The Promised Land at LivePerson
From a Kafkaesque Story to The Promised Land at LivePersonLivePerson
 
How can A/B testing go wrong?
How can A/B testing go wrong?How can A/B testing go wrong?
How can A/B testing go wrong?LivePerson
 
Telling the LivePerson Technology Story at Couchbase [SF] 2013
Telling the LivePerson Technology Story at Couchbase [SF] 2013Telling the LivePerson Technology Story at Couchbase [SF] 2013
Telling the LivePerson Technology Story at Couchbase [SF] 2013LivePerson
 
Introduction to Vertica (Architecture & More)
Introduction to Vertica (Architecture & More)Introduction to Vertica (Architecture & More)
Introduction to Vertica (Architecture & More)LivePerson
 

Plus de LivePerson (20)

Measure() or die()
Measure() or die() Measure() or die()
Measure() or die()
 
Resilience from Theory to Practice
Resilience from Theory to PracticeResilience from Theory to Practice
Resilience from Theory to Practice
 
System Revolution- How We Did It
System Revolution- How We Did It System Revolution- How We Did It
System Revolution- How We Did It
 
Liveperson DLD 2015
Liveperson DLD 2015 Liveperson DLD 2015
Liveperson DLD 2015
 
Http 2: Should I care?
Http 2: Should I care?Http 2: Should I care?
Http 2: Should I care?
 
Mobile app real-time content modifications using websockets
Mobile app real-time content modifications using websocketsMobile app real-time content modifications using websockets
Mobile app real-time content modifications using websockets
 
Mobile SDK: Considerations & Best Practices
Mobile SDK: Considerations & Best Practices Mobile SDK: Considerations & Best Practices
Mobile SDK: Considerations & Best Practices
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Apache Avro in LivePerson [Hebrew]
Apache Avro in LivePerson [Hebrew]Apache Avro in LivePerson [Hebrew]
Apache Avro in LivePerson [Hebrew]
 
Apache Avro and Messaging at Scale in LivePerson
Apache Avro and Messaging at Scale in LivePersonApache Avro and Messaging at Scale in LivePerson
Apache Avro and Messaging at Scale in LivePerson
 
Data compression in Modern Application
Data compression in Modern ApplicationData compression in Modern Application
Data compression in Modern Application
 
Support Office Hour Webinar - LivePerson API
Support Office Hour Webinar - LivePerson API Support Office Hour Webinar - LivePerson API
Support Office Hour Webinar - LivePerson API
 
SIP - Introduction to SIP Protocol
SIP - Introduction to SIP ProtocolSIP - Introduction to SIP Protocol
SIP - Introduction to SIP Protocol
 
Scalding: Reaching Efficient MapReduce
Scalding: Reaching Efficient MapReduceScalding: Reaching Efficient MapReduce
Scalding: Reaching Efficient MapReduce
 
Building Enterprise Level End-To-End Monitor System with Open Source Solution...
Building Enterprise Level End-To-End Monitor System with Open Source Solution...Building Enterprise Level End-To-End Monitor System with Open Source Solution...
Building Enterprise Level End-To-End Monitor System with Open Source Solution...
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
From a Kafkaesque Story to The Promised Land at LivePerson
From a Kafkaesque Story to The Promised Land at LivePersonFrom a Kafkaesque Story to The Promised Land at LivePerson
From a Kafkaesque Story to The Promised Land at LivePerson
 
How can A/B testing go wrong?
How can A/B testing go wrong?How can A/B testing go wrong?
How can A/B testing go wrong?
 
Telling the LivePerson Technology Story at Couchbase [SF] 2013
Telling the LivePerson Technology Story at Couchbase [SF] 2013Telling the LivePerson Technology Story at Couchbase [SF] 2013
Telling the LivePerson Technology Story at Couchbase [SF] 2013
 
Introduction to Vertica (Architecture & More)
Introduction to Vertica (Architecture & More)Introduction to Vertica (Architecture & More)
Introduction to Vertica (Architecture & More)
 

Dernier

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Selenium WebDriver Element Locators

  • 2. Connection Before Content creates meaningful, real time customer connections that help businesses increase conversions and improve consumer experience. LivePerson is hiring- peoplejobs@liveperson.com Ilan Malyanker Works in LP for 3 years. 8 years as an automation engineer. Blog- http://software-automation-development.blogspot.com mail- ilanm@liveperson.com / malyankeri@yahoo.com
  • 3. Purpose & Motivation • Identify elements to simulate operations • Identify elements to verify their status • Help create robust testing framework • Share knowledge • Expose new options for automation developers
  • 4. Terms & Code Alignment - Demo • HTML terms in WebDriver context • WebDriver basic usage • Think of WebDriver as a browser instance • WebElement- as any seen object on the page
  • 5. “By” class • Selenium WebDriver provides By class to support various locator strategies • Find methods take a locator or query object as an instance of By class as an argument
  • 6. Locating Elements Using • Id • Links • Tag names • Css Selectors • Xpath • JQuery • Text
  • 7. Browser Tools For Element Inspection • Firefox - „Firebug‟ add-on (right click → „Inspect Element‟ / F12). „FirePath‟ – Optimizing CSS & XPath • Chrome - Built-in page analyzing feature (right click → „Inspect Element‟ / F12) • IE - Developers tool („Tools‟ → „Developers Tools‟ / F12). There‟s also FireBug for IE. • Console – Immediate diagnose & execution tool. Available on all tools
  • 8. Languages • Java: driver.findElement(By.id(<element ID>)) driver.findElement(By.linkText(<linktext>)) • C#: driver.FindElement(By.Id(<elementID>)) driver.FindElement(By.LinkText(<linktext >)) • Python: driver.find_element_by_id(<elementID>) driver.find_element_by_link_text(<linktext >) • Ruby: driver.find_element(:id,<elementID>) driver.find_element(:link_text,< linktext >)
  • 9. 0 matches: throws exception (org.openqa.selenium.NoSuchElementException) 1 match: returns list of 1 WebElement instance 2+ matches: returns only first appearance in DOM 1 match: returns WebElement instance 0 matches: returns an empty list 2+ matches: returns list with all matching instances FindElement vs. FindElements findElement() findElements()
  • 10. Id driver.findElement(By.id(“<some_id>")); • Seems like the ideal solution • Id‟s don‟t always exist • Their uniqueness is not enforced • What about dynamic elements? • Might be used for other future purposes • Code injected from different sources (potential override) • Against web developers best practices
  • 11. Links Find elements by the text displayed on the link driver.findElement(By.linkText(“<link_text>")); driver.findElement(By.partialLinkText(“<link_partial_text>"))
  • 12. Tag Names Find web elements based on their HTML tags < class="form-inline"> < class="editable-controls"> <input class="editable-has-buttons" type="text"> <span class="editable-buttons"> <button class="btn btn-primary" type="submit"> <button class="btn btn-danger"> </span> </div> </form> driver.findElement(By.tagName("input")); *See that your tag is unique
  • 13. CSS Selectors (1) • Cascading Style Sheets- language used for describing the presentation semantics of a document written in a markup language such as HTML or XML. • Browsers implement CSS parsing engines for formatting or styling the pages using CSS syntax. Absolute path: driver.findElement(By.cssSelector(“html>body>div>p>input")); Relative path: driver.findElement(By.cssSelector(“input")) *the first instance found
  • 14. CSS Selectors (2) Regular attribute: tag with attribute value: driver.findElement(By.cssSelector(“button[name=„cancel‟]")); Special attributes: id: driver.findElement(By.cssSelector(“#save")); tag & id: driver.findElement(By.cssSelector(“button#save")); class attribute: driver.findElement(By.cssSelector(“.yoyo")); tag & class attribute: driver.findElement(By.cssSelector(“input.username"));
  • 15. CSS Selectors (3) tag with attribute value: driver.findElement(By.cssSelector(“img[alt=„kuku‟]")); tag which has attribute: driver.findElement(By.cssSelector(“img[alt]")); tag which doesn‟t have attribute: driver.findElement(By.cssSelector(“img:not([alt])"));
  • 16. CSS Selectors, advanced (last css slide) The first child of a tag with id: driver.findElement(By.cssSelector(“div#students:first-child")); The n-th child of a tag with id : driver.findElement(By.cssSelector(“form#loginForm:nth-child(3)")); Second descendent of div with id : driver.findElement(By.cssSelector(“div#ilan>p+*+p")); (first) tag which is enabled: driver.findElement(By.cssSelector(“button:enabled"));
  • 17. Xpath (1) • Xpath is a query language for selecting nodes from an XML document. • Xpath is based on a tree representation of the XML document and provides the ability to navigate around the tree. Absolute path: driver.findElement(By.xpath(“html/body/div/p/input")); Relative path: driver.findElement(By.xpath(“//input"))
  • 18. Xpath (2) Tag with attribute value: driver.findElement(By.xpath(“//input[@id=„username‟]")); Any tag with id: driver.findElement(By.xpath(“//*[@id=„myId']")); Operator „and‟: driver.findElement(By.xpath(“//input[@type='submit'][@value='Login']”)); driver.findElement(By.xpath(“//input[@type='submit„ and @value='Login']”)); Opertor or: driver.findElement(By.xpath(“//input[@type='stam„ or @class=„LP']"));
  • 19. Xpath (3) Attribute which starts with driver.findElement(By.xpath(“//input[starts-with(@class,„tbl_')]")); *there‟s also- ends-with() Attribute contains text: driver.findElement(By.xpath(“//input[contains(@id,'userName')]")); Match value to any attribute: driver.findElement(By.xpath("//input[@*='username']"));
  • 20. Xpath (4) Ancestor, descendant, following, following-sibling, preceding, preceding-sibling driver.findElement(By.xpath(“//td[text()='Product 1']/ancestor::table")); element.findElement(By.xpath(“/table/descendant::td/input")); *can only be applied from another WebElement Use parent to get to same-hierarchy object: driver.findElement(By.xpath("//div/input[@class=„kuku‟]/../button"));
  • 21. Text – CSS Selectors See if element‟s attribute contains specified text driver.findElement(By.cssSelector(“div[id*=„my_id„]")); (Also- ^ starts with, $ ends with) See if element contains specified text driver.findElement(By.cssSelector(“input:contains(„Some Text')")); *deprecated from CSS3 specification innerText attribute driver.findElement(By.cssSelector("td[innerText=„Some Text']")); *Doesn‟t work in FireFox textContent: driver.findElement(By.cssSelector("td[textContent=„text']")); *For FireFox
  • 22. Text – XPath Locate element by matching exact text value driver.findElement(By.xpath(“//td/span[text()=„Some Text‟]")); OR driver.findElement(By.xpath("//td/span[.=„Some Text‟]")); See if Element contains specified text driver.findElement(By.xpath("//td[contains(text(),„Some Text')]"));
  • 23. What‟s better, xpath or css selectors? • CSS Selectors method is faster • Browsers themselves use css selectors • Latest browsers optimize the use of css Selectors • Xpath- common language for xml/html parsing • Xpath is a two-way search mechanism (up&down the DOM tree) • Xpath handles text recognition better
  • 24. JavaScript Executor for JS & JQuery JavaScript syntax as a Java String: String script = "return document.getElementById(„some-id');"; OR Jquery syntax as a Java String: String script = "return jQuery('#some-id').get(0);"; JavascriptExecutor executor = (JavascriptExecutor)driver; WebElement element = (WebElement)executor.executeScript(script); • Opens a world of client side manipulations • jQuery() method uses- css selectors i. jQuery lib should be loaded on the page ii. Same executor runs both types of scripts iii. jQuery returns a collection, hence extract the first instance iv. The “$” – sign could also represent jQuery namespace
  • 25. Tips & Best Practices • Locators location • Use Enums • Know all your working tools • Element Detection & Highlighting • Expose locators and not just the methods • Work close to client developers (4 non agile developers) • Optimize your locators !! i Maximum focus ii Minimum dependencies
  • 26. Visit my blog - software-automation-development.blogspot.com

Notes de l'éditeur

  1. - All examples are in Java - FindElements() - find from another element - Best practice
  2. There’s also By.className, By.name