Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Xpath in Selenium

Topics to be Covered …

Introduction to Xpath

Benefits of Xpath

Syntax & Terminology

Types of Xpath

Xpath Functions

Xpath Axes
Introduction to Xpath

 Important strategy to locate elements in Selenium

 Xpath is a language to query XML documents

 It consists of a path expression along with some

conditions

 Xpath can also be defined as XML Path


Benefits of Xpath
Syntax &
Terminology of
Xpath
Syntax & Terminology
XML Tree

bookstore

book (category: book (category:


cooking) children)

bookstore bookstore bookstore bookstore


Types of Xpath

theAbsolute
It isRelative
direct
Xpath toXpath
way starts
findfrom
the element,
the middle
butofthe
thedisadvantage
HTML DOM of
thestructure.
absolute ItXpath
startsiswith
that the
if there
double
areforward
any changes
slash(//),
made
which
in the
meanspathit can
of search
the element
the element
then that
anywhere
Xpath gets
at the
failed.
webpage.

Ex: /html/body/div[1]/section/div[1]/div
RelativeEx:Xpath
//input[@id=‘ap_email’]
Xpath Syntax
Selecting Nodes:

 The node is selected by following paths or steps. The most useful path expressions are listed
below:

Expression Description

nodename Select all nodes with the name “nodename”


e.g., //input -> select all input tags in DOM
/ Selects from the root node
e.g., /html -> select the root element with html tag. It always start
from html tag of DOM
// Selects the nodes in the document from the current node that match
the selection
e.g., //div -> selects all div elements in DOM from current selection
.. Selects the parent of current node
e.g., //input[@id=‘text1’]/.. -> select parent node of input tag having
id= ‘text1’
Xpath Syntax
Predicates:

 Predicates are used to find a specific node or a node that contains a specific value.

 Predicates are always embedded in square brackets.

Expression Description

/bookstore/book[2] Selects the second ‘book’ element that contains the child of the
‘bookstore’ element.
/bookstore/book[last()] elects the last ‘book’ element that contains the child of the
‘bookstore’ element.
//bookstore/book[position()<3] Selects the first two ‘book’ elements that are children of the
‘bookstore’ element.
//title[@lang=‘en’] Selects all the title tags that have lang attribute value as ‘en’

//bookstore/book[price>35.00] Selects all the ‘book’ elements of ‘bookstore’ element which have
‘price’ element value greater than 35
Xpath Functions

Starts-with():
Contains(): is used to find elements whose attribute value
Starts-with()
text():
Contains()
changes Contains()
onisrefresh
used when
or any
theother
value
operation
of any attribute
on webpage,
changes
text() is used to locate element with exact text match.
dynamically.
however starting string remain constant
Syntax:
Syntax: Start-with()
Xpath= //button[text()=’Submit’]
Xpath= //label[starts-with(@id,’message’)]
//button[contains(text(),’Submit’)]
Result:
Result: text()button element with exact text as
This will select
This will select label
buttonelement
elementwhose
whichidcontains
attributetext
start
‘Submit’
‘Submit’
with message.
which Attribute
changes value
dynamically.
can be any thing after
‘message’.
Issue 1: Classes can be confusing and has
boilerplate code
Issue 1: Classes can be confusing and has
boilerplate code
Q: Let’s say I need to
create a Class
component for a
Counter. What all do I
need to do?
Extend “Component” class from React

import React, { Component } from "react";

class Counter extends Component {

export default Counter;


Define UI with render()

import React, { Component } from "react";


class Counter extends Component {
render() {
return (
<div>
<input
type="number"
name="name"
/>
</div>
);
}
}
export default Counter;
Initialise state with constructor()

import React, { Component } from "react";


class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<input
type="number"
name="name"
/>
</div>
);
}
}
export default Counter;
Use state value
import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<input
type="number"
name="name"
value={this.state.count}
/>
</div>
);
}
}
export default Counter;
Update state
import React, { Component } from "react";
class Counter extends Component {
constructor(props) { // Code hidden for display}
handleCountChange = (e) => {
this.setState({
count: e.target.value
});
};
render() {
return (
<div>
<input
type="number"
name="name"
value={this.state.count}
onChange={this.handleCountChange}
/>
</div>
);
}
}
export default Counter;
Which of these is specific to your component?

1. Extend “Component” class from React

2. Define UI with render()


3. Initialise state with constructor()
4. Use state value
5. Update state
Boilerplate code with Class components

1. Extend “Component” class from React

2. Define UI with render()


3. Initialise state with constructor()
4. Use state value
5. Update state
Classes can be confusing

● JavaScript isn’t inherently a class-based language

● this keyword brings with it, its own confusions

constructor(props) { <input handleCountChange = (e) => {


super(props); type="number" this.setState({
this.state = { name="name" count: e.target.value
count: 0 value={this.state.count} });
};
/> };
}
Class Component

With React 16.8

What is the
solution?
Setting up to embrace state

class WithClasses extends React.Component { function WithFunctions(props) {


constructor(props) { const count = ???; // "count" state
super(props);
this.state = { // a function to update "count" state
count: 0 const setCount = ???;
};
}
const handleCountChange = (e) => {
handleCountChange = (e) => {
setCount(e.target.value);
this.setState({
count: e.target.value
};
});
}; return (
render() { <div>
return ( <input
<div> type="number"
<input name="name"
type="number" value={count}
name="name" onChange={handleCountChange}
value={this.state.count} />
onChange={this.handleCountChange} </div>
/>
);
</div>
); }
}
}
Initialising state and state handler

class WithClasses extends React.Component { import { useState } from "react";


constructor(props) {
super(props);
function WithFunctions(props) {
this.state = {
count: 0 const [count, setCount] = useState(0);
};
} const handleCountChange = (e) => {
handleCountChange = (e) => { setCount(e.target.value);
this.setState({ };
count: e.target.value
});
return (
};
render() { <div>
return ( <input
<div> type="number"
<input name="name"
type="number"
value={count}
name="name"
value={this.state.count}
onChange={handleCountChange}
onChange={this.handleCountChange} />
/> </div>
</div> );
);
} }
}
Hooks are special
functions that lets you
hook into React
features (eg: state)
The useState() function (aka Hook)

● The useState() makes available a state value to be


managed within the function

● Takes the initial state value as the argument const [count, setCount] = useState(0);

● Returns an array with two elements


1. The latest state value
2. Function to update the state
Syntax differences - Class and Function
components
Initialising state
Class Components Function Components

constructor(props) { const [count, setCount] = useState(0);

super(props);

this.state = {

count: 0

};

}
Using state value
Class Components Function Components

<input <input
type="number" type="number"
name="name" name="name"
value={this.state.count} value={count}
/> />
Updating state
Class Components Function Components

handleCountChange = (e) => {


const handleCountChange = (e) => {
this.setState({
count: e.target.value setCount(e.target.value);
});
};
};
Declaring functions
Class Components Function Components

// class method syntax // function syntax


handleCountChange = (e) => {}; const handleCountChange = (e) => { };
Defining UI
Class Components Function Components

class WithClasses extends Component { function WithFunctions(props) {


render() { return (
return ( <div>
<div> <input
<input type="number"
type="number" name="name"
name="name" value={count}
value={this.state.count} onChange={handleCountChange}
onChange={this.handleCountChange} />
/> </div>
</div> );
); }
}
}
Activity 2: Counter app with Functions
● You are given the code for a Counter app written
using Class components
● In session3/CounterHooks.js,
○ Create a function component alternative of
the Counter component
○ Export it and use in src/App.js
Curious Cats

Q: But, isn’t this doing the same thing as useState() hook?

function WithFunctions(props) {
let count = 0; ● Updates count correctly
const handleCountChange = (e) => { ● But, component doesn’t re-render as
count = e.target.value;
count isn’t React state
console.log(count);
};

return (
<div>
<input
type="number"
name="name"
value={count}
onChange={handleCountChange}
/>
</div>
);
}
We can use hooks more
than once in a
component
Curious Cats

Q: Which of these lines of code will execute on re-render?


export default function App() {
console.log("Resetting values...");
let c = 0;
console.log(`${++c} - App() triggered`); Whole of the function gets executed
const [count, setCount] = useState(0);
On every re-render,
const handleCountChange = (e) => {
console.log(`${++c} - handleCountChange() triggered`); 1. App() function is registered
setCount(e.target.value);
};
2. useState() is initialized
3. handleCountChange() is registered
console.log(`${++c} - count=${count}`); 4. count is logged with initial value 0
5. return is called.
return (
6. onChange of input -> handleCountChange() is
<div>
{console.log(`${++c} - JSX returned`)}
triggered
<input 7. Since handleCountChange() calls the setCount
type="number" function it triggers the App to execute again.
name="name"
8. REPEAT steps 1 to 5.
value={count}
onChange={handleCountChange}
/>
</div>
);
}
On re-render

useState() keep the state values Other local values are resetted
hooked i.e, doesn’t reset
Don’t overuse state -
only use it if you want
the UI to re-render on
change
Class or Function
components - stick to
using 1 of this
consistently in a project
(We’ll use Functions going forward)
Summary

● Class components

○ Has boilerplate code

○ Can cause confusions due to this keyword usage

● Hooks are special functions that lets you hook into React
features (eg: state)
● useState() hook enables function components to have
their state

Note: We’ll look more into Hooks in the


coming sessions!
Interview questions
● On state change
● On prop change
1. When does a React component re-render? ● When its parent re-renders

● componentDidMount()
2. What are the different places we can make an ● componentDidUpdate()
● Event handlers
API call in React?

Stateless components
3. How does stateful and stateless components ● Do not deal with state and hence cannot
keep track of changing data
differ? ● Prints out what is given to them via props
or always render the same thing
Until next session 🍃

Thank you for joining in today, we’d love to hear your thoughts and feedback here -

https://forms.gle/tZf3ZLjT1AcqCxV87
Thank you

You might also like