Monday, June 24, 2024

CSS Selectors -2

 

Navigating to Child or Sub-Child Tags Using CSS Selectors

In CSS selectors, a space can be used to navigate from a parent tag to any of its child or sub-child tags (also known as descendants). This is similar to using // in XPath.

 

  xpath        / - child tag -->  > (CSS)

            // -àchild tag or subchild  or grand child tag .

           // à  replaced by "space" in CSS

 

css:     space - can be used navigate to child (or) sub child tag

ex:

 

Navigate to sub-child 'input' tag from 'html' tag:  space

 html>body>input

html input  18 ele

This CSS selector matches all input tags that are descendants of the html tag.

 

Navigate to sub-child 'option' tag from 'html' tag?

html option

 

 

Navigate to sub-child 'a' tag from 'html' tag:

html a

 

HW Navigate to sub-child 'option' tag from 'body' tag:

HW Navigate to child 'head' tag from 'html' tag:

HW Navigate to sub-child 'title' tag from 'html' tag:

 

 

Using the Dot (.) Shortcut for text() in XPath

In XPath, the text() function can be replaced by a dot (.) to simplify the syntax when matching elements based on their text content.

Examples:

1.     Using text() Function:

    • <p>Order no</p>: //p[text()='Order no'] - 0 elements found
    • <a>My gmail</a>: //a[text()='My gmail'] - 2 elements found
    •  

2.     Using Dot (.) Shortcut:

      text()  replace by .   dot

 

<p>Order no</p>: //p[.='Order no'] - 0 elements found

<a>My gmail</a>: //a[.='My gmail'] - 2 elements found

 

For a paragraph <p>My Paragraph. HTML can be used to develop web page</p>, the XPath would be:

Xpath: //p[text()='My Paragraph. HTML can be used to develop web page']

This approach matches the text content inside the specified tag directly.

 

shortcut with text() by (.) dot symbol:

//p[.='My Paragraph. HTML can be used to develop web page']

 

HW  Identify 'Open Facebook' link using text():

HW Identify 'Open Amazon' link using text():

HW  Identify 'My button' element using text():

contains(text(),’text from page ’) short cut :

 

text()  replace by .   dot -->  contains(.,’text from page ’)

                                       text()

 

Identify OpenFace book' link using contains with text()

//a[contains(text(),'Open Facebook')]

        (or)  replace by dot

//a[contains(.,'Open Facebook')]

 

 

HW  Identify 'My gmail' link by using contains text()    

 

HW Identify 'Open amazon '  link by using contains  text()?

 

 

HW  xpath for p  with text() = ' Html can be used ' using contains  text()?

 

CSSSelector in Selenium

 

CSSSelector :   id,name,classname, xpath, cssselector

 

    CSS - Cascading style Sheet

   If we want to apply styles to html page ...Difference  colors, back ground color etc.

CSS is used to define the presentation of HTML elements. It's not only used for styling but also serves as a powerful tool for locating elements on a webpage when using Selenium.

 

Ref:  https://www.w3schools.com/css/tryit.asp?filename=trycss_default

 

 

xpath syntax -->  // tagname [@attrname= 'attr val']

CSS  syntax  -->  tagname [attrname= 'attr val']   -->  remove // and @

 

<input type="text" name="fname" id="fid" class="firstclass">

 

 

CSSSelector using 'name' for First name text box -->  input[name='fname']   1 ele

CSS using 'id' for 'First name' text box  -->  input[id='fid']     1 ele

 

CSS using 'invalid id' for First name text box  -->  input[id='fid1234']  -- 0 ele

 

css using 'name' : 'Last name' text box --> input[name='lname']   1 ele

 

css using 'id' : Last name text box --> input[id='lid']

 

 

HW css using  'class' : Last name text box :

 

HW css using name : password text box :

 

HW css using 'id' : Male Radio button:

 

HW css using 'id' :computer checkbox :

 

HW css using 'name' :Civil checkbox :

 

HW css selector using id :Civil checkbox

 

 

multiple props (or) attributes :

xpath -->  //input[@id='idfirst'] [@attrName= 'attrVal']  [ ] [] [] []  .....

 

css   -->  input[id='idfirst'] [attrName= 'attrVal']  [ ] [] [] []  .....

 

Write CSSselector for  'first anme" text box where id = 'fid'  and name='fname' -->input[name='fname'][id='fid']

                                                   1 ele

 

 input[id='fid'] [name='fname'] --  Note :   don't write spaces between multiple attributes in CSS

                                                            --  1 ele

            bcoz space in CsS , we have Difference  meaning

 

Write CSSselector for "first name' text box where class='firstclass'

 css :input[class='firstclass']                  - 2 ele

 

Write CSSselector for first anme text box where class='firstclass'  and name= 'fname'

input[class='firstclass'][@name= 'fname']     -  0  ele .. dont use @  in cSS

 

 input[class='firstclass'][name= 'fname']                  - 1 ele   

 

HW : Write CSs Selctor : identify 'last name text box using 'name' and 'id' and class?

 

HW Write CSs Selctor  Radio buttons:male , Female  using name,  or id

           

HW Write CSs Selctor  - Check boxes: Electronics,  Computers,  Civil,  Electrical

 

Handling Textbox using CSS:

package WebelementsBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class TextboxesUsingCSSSelector {

 

            public static void main(String[] args) {

                        //  open Chrome browser

                        //                      1.

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        //2  create obj for ChromeDriver- Class

                        WebDriver driver =  new ChromeDriver();// open chrome browser with empty url        

 

                   driver.get("file:///C:/brahma/Practise/SelniumPractiseNew/SampleWebpage.html");

 

 

                        // Enter  "Raju" value in 'first name' text box using CSSSelector by using name

                        //   input[name='fname']

                        driver.findElement(By.cssSelector("input[name='fname']")).sendKeys("Raju");

 

                        // enter some value 'yadhav' in 'lAST NAME' text box using CSS by using id

                        //  input[id='lid']

                        driver.findElement(By.cssSelector("input[id='lid']")).sendKeys("yadhav");

 

                        //HW  Enter some value in 'pwd'  using CSSSelector

 

                        // Hw get the entered value from last name text box using CSSSelector

 

 

            }

 

}

 

 

Handling Radio button using CSS:

 

                        //HW Click 'male' Raido button using 'CSSSelector"

 

                        //HW get radio button 'male' status selected  using "CSSSelector"

                        //  isSelected()

 

                        //HW get radio button 'female' status   using CSSSelector

 

HW click checkboxes 'Electronics', Computers,  Civil   use "CSS sleector"

          click

        is selected

            is displayed

            is enabled

            get attribute value  name, id ....

 

 

Link:

 

                        // HW Click 'My gmail' link using CSSSelector       

 

 

                        //HW  click Login button using Csselector ?

 

// HW get url of 'My gmail'

 

CSS short forms:

----------------

#idvalue

#maleid  or anytag [id='idfirst']

 

<input id="maleid" type="radio" name="sex" value="male">

 

CSS:  input[id='maleid']  - ok

  input#maleid  (or) 

 #maleid  - any tag name id=maleid

 

<input type="radio"name="female" id="femaleId">

 

CSS using id:

-------------

   input[id='femaleId']

 or

input#femaleID

or

#femaleID

 

ex:  find the 'cars' dropdown ele using Id--> #carid  

     

 

HW  CSS for the 'lastname' texbox with "id"

 

HW CSs for 'bikes' dropdown ele - using "id "

 

. classValue :

input[class='firstclass'] - 4 ele

or

tagname.classValue  -

ex:

 

input.firstclass  //  input where class = 'firstclass'.

 .firstclass or any tag name whose class = 'firstclass' 2 ele

 

             .  =   class name

 

Navigate to Child Element:

In CSS selectors, the > symbol is used to navigate to child elements directly under a parent element.

 

 xpath- /  --> > (CSS)

xpath -->  //select[@name='cars']/option  -  /

CSS   --> use  >  --> 

 

In CSS, >   can be used to navigate to child element or tag

 

 

Navigate to html and head --> html>head

CSS for title  --> html>head>title

CSS for input  -->html>body>input   18 ele

 

HW : CSSselector : Identify 'bikes' dropdown and navigate to child tag i.e option tag

 

 

HW write CSS: Navigations -->  html , body, p  tags

 

HW write CSS: Navigations -->  html , body, input where type='password'  tags

 

 

HW write CSS: Navigations -->  html , body,  child tags i.e  'a' tag

 

HW write CSS: Navigations -->  html , body,  child tags i.e  'img' tag

 

CSS Selectors: ^, $, *:

 

^ : carrot (or) cap                                                        xpath

 

  tag[attrName ^= 'attr Value' ]           = // tag[starts-with(@attrname, 'attr val')]

 given tag name where attribute name starts with given  attribute value

 

eX:  all input tags where 'id' starts with given val i.e  'mi'

    css:   input[id^='mi']

 

 

 CSS - all input tags where 'name' starts with 'fna' -->    input[name^='fna']  --

 dont give any spaces in css

 

 

CSS  where all input tags  id starts with 'fid' -->  input[id^='fid']  1 ele

 

HW CSS :  where 'id' starts with 'male'

 

HW CSS :  where 'id' starts with 'female'

 

HW CSS:  where 'name' starts with 'computers'

 

HW CSS:  Identify  select tag , where 'id' starts with 'bike'?

--------------------

--------------------------------------------------

*   =  contains(@Attrname,'Attr value')

---------------------------------------

syntax -->   tagName [attrName *= 'value']

 

all given tags where attr name contains given value

 

ex:

 

Identify input tag  where name' contains 'fna' ?  input[name*='fna']

 

 

HW Identify input tag  where name' contains 'lna'  ?

 

HW Identify input tag  where name' contains 'name' ?

 

HW Identify select tag  where name' contains 'cars' ?

 

Hw Identify select tag  where 'id' contains 'car' ?

 

----------------------------

$ -   == ends-with ()

 syntax :

--------

 tagName [attr Name  $= 'attr Value']

all tags where attr name 'ends' with given value

 

ex:

<input type="text" name="fname" id="fid" class="firstclass">

 

input[class$='class'] 2  ele

input[class$='isrtclass']

input[name$='345']

input[id$='id']

CSS:

 

 CSS : all input tags where 'id' ends with given value i.e 'maleid'    

             2 ele  

input[id$='maleId']

 

HW :CSS   where class ends with given value 'class'?

 

HW CSS:  Identify  select tag , where id' ends with 'arid'?

 

HW CSS:  Identify  select tag , where name ends with 'kes'?

 


            ^   = start-with()

            $  = ends with () --  note :   in xpath, we dont have ends-with()

            *   = contains()

 

FAQ how can you handle Dynamic object/elements ?

Handling Dynamic objects/Elements using Selenium-Java

 

Dynamic object:

If any object/ element properties keep on changing every time, we can say the element is dynamic element.

 

When dealing with dynamic objects in Selenium, where element properties like id change with each page load, we can use XPath functions like contains() and starts-with() to locate these elements.

 

ex: 

<input id="userid101">

<!-- Upon reopening or refreshing the page, the id changes -->

<input id="userid78">

 

When we open page again, inspect the element, it shows dynamic values for id.

Handling Dynamic Objects Using XPath:

To locate elements with dynamic properties, we can use:

  1. contains(): This function checks if the attribute contains a specific substring.
  2. starts-with(): This function checks if the attribute starts with a specific substring.

 

Note: XPath does not have an ends-with() function. 

 

1.     contains(@attrname, 'attrVal'):

 

syntax --> //tagname[contains(@attrName,'AtrrValue')]

goes to all tag names  where attribute name contains given attribute val.

 

html :

<input type="text" name="mname123" id="mid">

<input type="text" name="mname345" id="mid">

 

Navigate to input tag where 'name' contains 'mname' --> //input[contains(@attrNAme, 'Attr value')]

 It goes to all input tags where 'name' contains 'mname'  

 

 

2.     starts-with():

syntax-->  //tagname[starts-with(@AttrName, 'AttrValue')]

 

goes to all i/p tags where attribute name starts -with given value

 

<input type="text" name="mname123" id="mid">

<input type="text" name="mname345" id="mid">

 

     - 1 ele

 It goes to all input tags where name start with 'mname' - //input[starts-with(@name,'mname')]

 

 

//input[starts-with(@name,'m')]   - 2 ele

//input[starts-with(@name,'mn')]  - 1 ele

//input[starts-with(@name,'mna')]  - 1 ele

 

 

code:

package WebelementsBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class DynamicTextbox {

 

            public static void main(String[] args) throws InterruptedException {

                        // open chrome

                        //  open Chrome browser

                        //                                              1.

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        //2  create obj for ChromeDriver- Class

                        WebDriver driver =  new ChromeDriver();// open chrome browser with empty url

 

                   driver.get("file:///C:/brahma/Practise/SelniumPractiseNew/SampleWebpage.html");

                        Thread.sleep(4000);

                        // enter data in 'middle name' textbox  using mname345 -use contains

//                      driver.findElement(By.name("mname901")).sendKeys("Ram");

                        // It throws NosuchElement Exception.

                        // if there is no element found on the page by using name = mname901, then it throws NosuchElement Exception.

 

                        // enter data in middle name  using contains()

            driver.findElement(By.xpath("//input[contains(@name,'mname')]")).sendKeys("Rama");

 

                        // starts-with()

                        driver.findElement(By.xpath("//input[starts-with(@name,'mname')]")).sendKeys("Sita");

 

 

            }

 

}

 

FAQ*** how can you handle dynamic object/ elements?

 

Identifying Elements Using the last() Function in XPath:

 

Identify all input tags à  //input     - 18 ele

This XPath expression selects all input elements in the document

 

identify last input tag à  //input[18] (or) //input[last()]

This XPath expression selects the last input element in the document.

 

//input[last()-1]  - submit à to identify the second last input element.

//input[last()-2]  -- login à to identify the third last input element.

 

 

ex2:

Identify select tags in htmlpage --> //select  - 3 select tags

//select[last()] -MultiSelect

//select[last()-1]  - bikes dropdown

//select[last()-2]  - cars dropdown

 

ex3:

Get all textboxes --> //input[@type='text']         6 ele

<input type ='text' >

 

ex4:HW  xpath to get all radio buttons

 

ex5: HW  xpath to get all checkboxes

 

ex 6: xpath to get all links --> //a     3 ele

  <a  href= "url"   >  google linktext  </a>

 

//a

 

1st 'a' tag  à //a[1]

2nd 'a'  tag à //a[2]

3rd 'a' tag  à //a[3]

 

Position Function in XPath

The position() function in XPath is used to specify the position of an element within its parent. This can be useful for selecting a specific element when there are multiple elements of the same type.

 

Position():

ex:  //input[1] à 1st input tag

 

//input[position()=1]  or //input[1]

Selects the first <input> tag in the document.

 

//input[position()=2] or //input[2]

Selects the second <input> tag in the document

 

//a[position()=1] - Selects the first <a> (anchor) tag in the document.

//a[position()=2] - Selects the second <a> tag in the document.

//a[position()=3] - Selects the third <a> tag in the document.

//a[position()=50] - o ele

 

XPath Using Text Function:

The text() function in XPath is used to select elements based on their visible text content.

This can be particularly useful when an element does not have identifiable attributes like id, name, class, or href.

 

 

My gmail link :

<a href="https://www.google.com/intl/en-GB/gmail/about/"> My gmail </a>

 

//a[@href='https://www.google.com/intl/en-GB/gmail/about/']  - 1 ele

 

 

 

<a > My gmail </a>

 

 no id,no  name, no class, no href -->

 

<a> My gmail</a>

 

syntax -->   //tagname[text()='visible text from page']

 

xpath for My gmail link --> //a[text()='My gmail']   1 ele

 

xpath for Facebook --> //a[text()='Open Facebook']   1 ele

 

HW Write xpath using text() for 'Open amazon' link -->

 

HW xpath for 'MyButton' button using text() -->    1 ele

 

HW xpath for para using text()-->

 

 

 

Note:

------

 if we don't have name, id, class,  any attribute name ,  we can identify the element based on text()

<button>MyButton</button>

 

 

Using contains(text(), 'visible text from page') in XPath:

The contains() function in XPath allows you to select elements based on whether their text contains a given substring. This is useful for handling elements with dynamic or partially known text.

 

Syntax--> //tagname[contains(text(),'visible text from page')]

 

<a href="https://www.google.com/intl/en-GB/gmail/about/">My gmail</a>

Full text:

My gmail --> //a [contains(text(),'My gmail')]       - goes to all 'a' tags where text contains

 

Partial text:

given value 'My gmail  --> //a [contains(text(),'gmail')]

My -->  //a [contains(text(),'My')]

 

Here we can give full text (or) partial text from page.

 

 

Open Facebook Link:

//a[text()='Open Facebook ']  --  o ele as we have some spaces in page

//a[contains(text(),'Open Facebook')] --  1 ele  it ignores spaces here

 

 

HW  Write XPath for the following using contains(text(),''):

facebook -->

book -->

Open amazon -->

amazon  -->

 

Child and Sub-child Navigation in XPath:

// - child (or) sub child:

 

/ is used to navigate to child tag name/ child element

             ex: html/body

 

// is used to navigate to child or sub-child tags (grandchildren and beyond).

  ex:  /html//title

 

/html // input -- child input tags or subchild tags of input

 

//body/select[1]/option

//body//option  - 14   navigate to child/ sub child tags of 'option'

 

/  ànavigate to child tag

// à    child tag or Sub child tag

 

XPath Using Wildcards (*) for Tag and Attribute Names:

In XPath, the asterisk (*) wildcard character is used to represent any tag name or any attribute name. This flexibility allows XPath queries to target elements regardless of their specific tag names or attribute names, which is particularly useful when dealing with dynamic or changing attributes.

 

-->       Tag as *

-->       Attribute name as *

-->       any tag name and any attribute

 

ex1 : Tag as *

-------------

//input[@id='fid']  -    2

//Select[@id='fid'] -   0

 

// * [@id='fid'] -  any tag name where id = 'fid'

To select any tag with an id attribute equal to 'fid':

 

*  represents any tag name i.e could be input, select,a  etc...

 

//*[@class='firstclass'] -  2 le

 

meaning -->  *  means any tag name

here it refers any tag name where class ='firstclass']

 

HW XPath for 'any tag' name where id = mid?

 

HW Xpath for 'any tag' name  whose name= 'cars'?

 

XPath Using Wildcards for Attribute Names:

In XPath, the asterisk (*) wildcard character can also be used to represent any attribute name. This allows for XPath queries that target elements based on any attribute they might have, regardless of its specific name.

 

ex2: Attribute name as *

-------------------------

//input[@id='fid']    -->  //input[@*='fid']

//input[@name='male'] -->  //input[@*='male']

 

//input[@*='lname']  = 1 ele

 

* --> any Attribute name / property name i.e id, name,class....   etc

 

 Xpath for input tag name ,  any attribute name  = 'pname' ?

//input[@*='pname']

 

 

Xpath for select tag name ,  any attribute name  = 'cars'

//select[@*='cars']

 

HW  Xpath for select tag name ,  any attribute name  = 'bikes'

 

HW  Xpath for select tag name ,  any attribute name  = 'maleid'

 

 

XPath for Any Tag Name and Any Attribute:

In XPath, you can use the wildcard * to represent any tag name and any attribute name within an expression.

 

//input[@name='fname']

 

//*[@*='fname']

 

//   any tag name , any attribute name =   'fname'

 

//*[@*='pname']  - 1 ele

any tag name    any attr = 'pname '

 

//a[text()='My gmail']

//*[text()='My gmail']

  * --> any tag name - whose text= My gmail

 

 Xpath   any tag  and any attribute = 'Login'

 

HW Xpath   any tag  and any attribute = civil'

 

HW Xpath   any tag  and any attribute = eleId

 

XPath using Or (|)

In XPath, the | (pipe) operator is used to combine two or more XPath expressions to select elements that satisfy either condition. This is particularly useful when you want to find elements based on multiple attributes or conditions.

find element where name = fname' (or) name='lname' ?

-->  //input[@name='fname'] | //input[@name='lname']

 

 

identifies elements where name = fname or  name = 'lname'   2 ele

 

 

 Xpath , input tag ,where name ='mname'  or id='lid'?

      //input[@name='mname'] | //input[@id='lid']          - 1 ele

 

HW Xpath , select tag ,where name ='cars'  or id='bikesid'?

 

HW Xpath , select tag ,where name ='cars'  or id='bikid'?

 

 

Using and with Multiple Properties in XPath:

When you want to specify multiple conditions for selecting elements using XPath, you can use the and operator along with multiple properties or attributes. Each condition inside square brackets [] represents a property or attribute condition that must be satisfied by the selected element.

 

and -   - give Multiple properties [] [] [] …. Etc

 

//input[@name='fname'][@id='fid'] --  or //input[@name='fname'  and @id='fid']

//input[@name='fname'][@id='fid'] [@class='firstclass'] .......

   or

//input[@name='fname' and  @id='fid'and @class='firstclass']

 

 

//input[@class='firstclass'] [@id='fid']

//input[@class='firstclass'] [@id='fid'] [@name='fname']

 

Xpath  , input tag where id='uid' and name= 'uname'?

//input[@id='uid'][@name='uname']

 

HW Xpath  , input tag where id='mid' and name= 'uname'?

                  0 ele

 

HW Xpath Select tag where name ='cars'  and id=carid

 

HW Xpath Select tag where name ='cars'  and id=bikesid

 

HW Xpath input  tag where name ='lname'  and id=lid  and class='firstclass'?

 

 

 

Write xpath,how many checkboxes ?

 

 <input type = "text"    -- text box

 <input type =  "radio"   -- radio button

 <input type = "checkbox"  -- check box

 

xpath --> //input[@type='checkbox']   -   4 ele

 

HW: xpath how many textboxes ?

<input   type = "text"    -- text box

 

 xpath -->

 

HW :xpath , how many radio btns?

<input type = 'Radio'

 

 

// HW  how many links ?

xpath -->

 

HW  xpath , how many dropdowns are there?

select

xpath -->

 

// HW xpath ,  how many images ?

 

 

HW WAP  to use all above xpath's in textbox ,radio , checkboxes....?

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...