SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

Más 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
 

Más 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)
 

Último

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 

Último (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 

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

Notas del editor

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