Your ultimate guide

Showing posts with label Python Automation. Show all posts
Showing posts with label Python Automation. Show all posts

Handling Drop downs using Selenium with Python


Handling drop-down:
 The Select class in selenium is used to handle the drop-down. The drop-down is created in an HTML document using the <select> tag.
    

    In order to utilize the Select class methods, we need to import "selenium.webdriver.support.select.Select" in our code.

The selenium Select class contains the following sub-functions:
  • options: This function gets the all options in the dropdown in a list of web elements.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • all_options = dropdown.options

      • print(len(all_options))

      • for option in all_options:
      •       option.click()

      • all_options[2].click()
  • select_by_visible_text("VisibleText"): This function selects the options based on the visible text in the drop-down.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • dropdown.select_by_visible_text("India")
  • select_by_value("value"): This function selects the option based on the value attribute.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • dropdown.select_by_value("ind")
  • select_by_index(index): To select an option, use the index number. Keep in mind that the index starts from zero, so to select the first option, use 0 as the index. For the second option, use 1 as the index, and so on. By using the correct index, you can easily select the desired option.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • dropdown.select_by_index(4)
Similarly, there are functions to deselect the selected option:
  • deselect_all()
  • deselect_by_visible_text("visibletext")
  • deselect_by_value("value")
  • deselect_by_index(index)



is_multiple: we can use this function to ensure whether the specified dropdown is a multi-select option dropdown or not. This method returns True when the corresponding dropdown is multi-select.
  • Syntax:
    • dropdown = Select(driver.find_element(By.ID, "tcg"))
    • multidrp = dropdown.is_multiple
    • if multidrp:
    •       print("The Dropdown is Multi-Select")
    • else:
    •       print("The Dropdown is not Multi-Select")

Handling Alerts using Selenium with Python

Alert in Selenium: An alert in Selenium is a small message box that appears on the screen to give the user some information or notification.







    With the assistance of Selenium, we can execute various tasks within an alert box such as accepting or dismissing it, obtaining alert messages, and sending actions. These actions rely on the use of the class selenium.webdriver.common.alert.Alert(driver).

Selenium alert methods:
  • accept() - This method accepts an alert pop-up.
    • Syntax:
      • alert = Alert(driver)
      • alert.accept()
  • dismiss() - This method dismisses an alert pop-up.
    • Syntax:
      • alert = Alert(driver)
      • alert.dismiss()
  • send_keys() - Send keys to alert
    • Syntax:
      • alert = Alert(driver)
      • alert.send_keys("Testing Colleges")
  • text - This method gets the alert message.
    • Syntax:
      • alert = Alert(driver)
      • message = alert.text
      • print(message)

Program:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.alert import Alert
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/2023/08/alerts-demo-pages.html")
  6. # Confirm Alert box
  7. altbox = driver.find_element(By.ID, "confirmbox")
  8. altbox.click()
  9. time.sleep(2)

  10. alert = Alert(driver)
  11. # print the alert message
  12. print(alert.text)
  13. # accept the alert box
  14. time.sleep(2)
  15. # close the window
  16. driver.close()

OUTPUT:
    













Browser Navigation Commands



Navigation Commands:
    Navigation Commands are used to navigate window base actions in the browser.
            

1. get("URL"): Get method will navigate to a web page given by the URL.
    Example: driver.get("https://testingcolleges.blogspot.com")

2. back(): It does the same operation as clicking on the back button (←) of any browser.
    Example: driver.back()

3. forward(): It does the same operation as clicking on the forward button (→) of any browser.
    Example: driver.forward()

4. refresh(): To refresh the current web page.
    Example: driver.refresh()


Example Program for Browser Navigation Commands:
  1. import time
  2. from selenium import webdriver

  3. driver = webdriver.Chrome()
  4. driver.get("https://www.google.com/")
  5. driver.get("https://www.facebook.com/")

  6. driver.back()
  7. driver.forward()
  8. time.sleep(2)
  9. driver.refresh()
  10. time.sleep(2)
  11. driver.quite()
OUTPUT:
    


Handling Text Box Using Robot Framework



Input Text: This keyword is used to give text into the text field identified by the locator.
    Syntax: Input Text    locator    text

Clear Element Text: This keyword is used to Clear the value of the text-input element identified by the locator.
    Syntax: Clear Element Text    locator

Click Button: This keyword is used to Click the button identified by the locator.
    Syntax: Click Button    locator
Note: By default, buttons are searched using id, name and value.



Example Test Case:
  1. Open Browser Navigate to Demo Form URL: https://testingcolleges.blogspot.com/2023/08/demo-form.html
  2. Enter First Name as "Testing" and Last Name as "Colleges".
  3. Give the email ID: "123@gmail.com"
  4. Then Remove the above email ID and Add a new id: abc@gmail.com.
  5. Click on Submit button.
  6. Close the Browser.

Program:
  1. *** Settings ***
  2. Library    SeleniumLibrary
  3. *** Variables ***
  4. ${url}      https://testingcolleges.blogspot.com/2023/08/demo-form.html
  5. ${firstName}    Testing
  6. ${lastName}     Colleges
  7. ${email}    123@gmail.com
  8. ${email2}   abc@gmail.com
  9. *** Test Cases ***
  10. TextBox
  11.     Open Browser    ${url}  Chrome
  12.     Input Text    id:fname  ${firstName}
  13.     Input Text    id:lname  ${lastName}
  14.     Input Text    id:mail   ${email}
  15.     Sleep    2
  16.     Clear Element Text    id:mail
  17.     Input Text    id:mail   ${email2}
  18.     Click Button    Submit
  19.     Sleep    2
  20.     Close Browser
Output:


Robot Framework SeleniumLibrary - Browser Keywords

SeleniumLibrary:
  • SeleniumLibrary is a web testing library for Robot Framework.
  • SeleniumLibrary uses the Selenium WebDriver modules internally to control a web browser.
  • Currently, Selenium Library provides 177 Keywords. Every keyword has one specific action.
  • To use this library in the robot framework script we need to import it. In the robot framework libraries are implemented in the *** settings *** section.
    • Syntax: for importing in the selenium library
      1. *** Settings ***
      2. Library SeleniumLibrary


Browser Keywords:

Create Webdriver: 
  • It Creates an instance of Selenium WebDriver. By this, we can give the location of the Webdriver.
  • This keyword should only be used if provided by Open Browser.
  • driver_name must be a WebDriver implementation name like Chrome, Firefox, Edge, Safari, or Remote.
  • If the WebDriver is configured in a "Python_installed_location/Scripts" folder, there is no need to use the "Create Webdriver" function.
    Syntax: 
    Create Webdriver        driver_name        executable_path="path to the webdriver"

    Example:
    Create Webdriver        Chrome        executable_path="C:\Driver\chromedriver.exe"



Open Browser: This keyword helps to open a URL in a specific Browser.
    Syntax: 
            Open Browser        URL        Browser_Name(Chrome/Firefox/Edge/Safari)
    Example: 
            Open Browser        http://example.com        Chrome



Maximize Browser Window: It maximizes the current browser window.



Get Title: Returns the Title of the Current page.



Get Source: Returns the entire HTML source code of the current page.



Get Location: Returns the Current Bowser window URL.



Close Window: Close the currently opened and selected browser window/tab.



Close Browser: Close the current browser.



Close All Browser: Closes all open browsers.



Example Program:
  1. *** Settings ***
  2. Library       SeleniumLibrary

  3. *** Variables ***
  4. ${url}       https://www.google.com/

  5. *** Test Cases ***
  6. BrowserCommands
  7.        Create Webdriver       Chrome    executable_path="C:\Driver\chromedriver.exe"
  8.        Open Browser       ${url}       Chrome

  9.        Maximize Browser Window

  10.        ${title}       Get    Title
  11.        Log To Console       Title of the current page : ${title}

  12.        ${pageSource}       Get    Source
  13.        Log To Console       ${pageSource}

  14.        ${pageURL}       Get    Location
  15.        Log To Console       Current page URL : ${pageURL}

  16.        Close window
Output:
  1. Title of the page : Google
  2. <html> --------------- </html>
  3. Current page URL : https://www.google.com/

Creating Robot file & Components of Robot framework

Creating Robot Framework file:
# After doing all the setup, our PyCharm will be ready to create the robot file. 
# Every robot test case file has the extension '.robot'.
- Steps for creating a robot file:
> Right-Click on your Project/Package/Directory(based on where we need to create a robot file), select New then click on File.
> Give the name of the robot file with an extension .robot
> Example: form.robot (filename.robot)

Components of Robot Framework:
    Robot Framework scripts are mainly divided into four sections/components. By this, we can systematically arrange our script. The starting and ending names of every component must be *** (3 asterisks).
1.  *** Settings ***
2.  *** Variables ***
3.  *** Test Cases ***
4.  *** Keywords ***
*** Settings ***
    In this Settings section, we can add libraries and resources.
*** Variables ***
    In this Variables section, we will define variables that are commonly used in test cases.
*** Test Cases ***
    In this Test Cases section, we write multiple test cases with test scripts/keywords.
*** Keywords ***
    In this Keywords section, we create user define keywords.

------- *** -------

Example:

User story:
1.  As a user, I want to access the Facebook login page using the Chrome browser.
2.  I will input my username and password as abcd@gmail.com, followed by 123456.
3.  I will click on the Login Button.
4.  And then Close the browser. 
Programs:
1.  *** Settings ***
2.  Library  SeleniumLibrary
3.  
4.  *** Variables ***
5.  ${username}    abcd@gmail.com
6.  ${password}    123456
7.  
8.  *** Test Cases ***
9.  LoginTest
10.       Open Browser    https://www.facebook.com/    Chrome
11.         loginToApplication
12.         Close Browser
13.  
14.  *** Keywords ***
15.  loginToApplication
16.         Input Text    xpath://input[@id='email']    ${username}
17.         Input Text    xpath://input[@id='pass']    ${password}
18.         Click Button    Log in

We will learn all the above keywords in the coming sessions, now just try to understand the program.
#  In the *** Settings *** section, we imported a library called SeleniumLibrary. SeleniumLibrary contains a lot of keywords in the above programme we use some of the keywords supported by this library - Open Browser, Input Text, Click Button, Close Browser.
#  In the *** Variable *** section, we define 2 variables.
- username = abcd@gmail.com
- password = 123456
#  In the *** Keywords *** section, we created a user define keyword called loginToApplication. and that keyword has some actions to input a username and password and then click the login button.
- Here instead of giving username and password values directly, we give variables names with are declared in the *** Variables *** section.
- By using that variable names we can get their values here.
#  In the *** Test Cases *** section, we created a test case with the name LoginTest.
-  Here first it will open the Chrome browser then it will navigate to the Facebook login page.
-  Then it calls the loginToApplication keyword. Whatever action is inside that keyword they will be run here.
-  Finally, Browser will Close.

Robot Framework Setup in Pycharm IDE



Robot Framework In Python:

About Robot Framework
# Robot Framework is an open-source automation framework for Acceptance Testing.
# Robot Framework is easy to learn and not much programming knowledge is required.
# It uses a keyword-driven testing technology approach.
# Users can create new higher-level keywords from existing ones using the same syntax used for creating test cases.
# To write the script in selenium automation we need to know lots of methods for every action, but in the robot framework by using some keywords we can automate the web page.
# Robot framework supports a lot of Libraries - BuiltIn Library, Selenium Library, DB Library, DateTime Library etc.,
- Every Library has different keywords by importing that library we can access those keywords.
- By default, these libraries are not included in the robot framework, we need to download the library and use it.
- To automate the webpage we use Selenium Library.
 
Robot Framework setup:
1.  Install Python
2.  Install Pycharm IDE
3.  Install selenium (optional)
4.  Install robot framework
5.  Install Robot framework selenium library

Step 1: Install Python
- Goto Python's official website, then download and install the latest version of Python. 
- I am already posted how to install Python software, click here for the installation process.

Step 2: Install Pycharm IDE
- Click on this link: https://www.jetbrains.com/pycharm/
- Then download Pycharm Community Edition and install it.
- I am already posted how to install Pycharm IDE, click here for the installation process.
Step 3: Install selenium
- Go to the command prompt (win + R, then type cmd and press ENTER).
- Give the command pip install selenium and press ENTER. Then selenium will be installed.
Step 4: Install the robot framework
- Go to the command prompt (win + R, then type cmd and press ENTER).
- Give the command pip install robotframework and press ENTER.
        

Step 5: Install the robot framework Selenium library
- Go to the command prompt (win + R, then type cmd and press ENTER).
- Give the command pip install robotframework-seleniumlibrary and press Enter.
        

------------------ *** ------------------

Setup In PyCharm IDE:

    selenium, robotframework and robotframework-seleniumlibrary these 3 packages, whenever we create a new PROJECT in the PyCharm IDE we need to install these packages in that project also.

To add these packages to the project using GUI:
    1.  First, open Pycharm IDE and open your Project or create a new Project (Click on the Menu (☰),  Select File in that click on New Project and give the project name then click on Create)
    2.  To install packages, Click on Menu (☰), Select File in click on Settings.
    3.  Then select your Project (Project: your project name), then click on Project Interpreter.
    4.  Click on the "+" symbol to add a package, then search package name and install it.
a.  Search selenium, then click on install package.
b.  After installing selenium, search robotframework and then click on install package.
c.  After installing robotframework, search robotframework-seleniumlibrary and then click on install package.

To add these packages to the project using CLI (Terminal):
    1.  First, open Pycharm IDE and open your Project or create a new Project (Click on the Menu (☰),  Select File in that click on New Project and give the project name then click on Create)
    2.  Go to the Terminal in Pycharm, for that Click on the Menu(☰), select View, then select Tool windows and then click on Terminal. (Shortcut key: Alt + F12)
    3.  By default, the terminal locates the current project path.
a.  Type command pip install selenium then press ENTER, then selenium will be installed.
b.  Type the command pip install robotframework then press ENTER, and then the robot framework will be installed.
c.  Type the command pip install robotframework-seleniumlibrary and then press ENTER.

------------------ *** ------------------

Installing Plugin to PyCharm IDE:
# By default, PyChram IDE can't identify the robot framework files.
# To identify the robot file we need to add a plugin to PyCharm IDE this is a one-time activity.
# There are a lot of plugins that are there to identify the robot file (intelliBot, intelliBot @seleniumlibrary patched, Hyper RobotFramework Support etc.,) we need to add one of the plugins.
- To add Plugin to Pycharm:
- Open PyCharm IDE
- Click on Menu (☰), then select File and then click on Settings.
- In the setting tab click on Plugins
- Search for Hyper RobotFramework Support and install it.

        



Write a First Automation Program using Python with Selenium



Create a New Python file:
    1) Right-click on your project folder, select New and then click on Python File. 
        
    2) Give the "file name", and select "Python file" then press ENTER.
        
    3) Then your Python file will be created to write the script.

    Note:
        If you want to create a folder in your project, Right-click on your project folder, select New and then click on Directory. Give the Folder name and then press ENTER.


To Launch Web Browser:
    1) First we need to import 'webdriver' from the 'selenium' package.
    2) and we need to import 'Service' from the 'selenium.webdriver.chrome service'
        Example:
            from selenium import webdriver
            from selenium.webdriver.chrome.service import Service
    3) Based on which browser we are going to launch that browser script we need to write
            a) For Chrome Browser:
                    driver = webdriver.Chrome(service=Service("path\to\chromedrive.exe"))
            a) For Firefox Browser:
                    driver = webdriver.Firefox(service=Service("path\to\geckodrive.exe"))
            a) For Edge Browser:
                    driver = webdriver.Edge(service=Service("path\to\msedgedriverdrive.exe"))

    Note: Here path means, the location of already downloaded(and extracted) Browser specific web drivers in your computer.
            For Example, if the chromedriver.exe file is located in the "C:\Driver\" folder then the path will be: "C:\Driver\chromedriver.exe"


To Launch any website (eg: google):
    1) get(String Url) function, is used to open the given URL in the browser.
            Syntax: driver.get("Url")
            Example: driver.get("https://www.google.com")



Example Program to launch Google in Chrome Browser:

    1) from selenium import webdriver
    2) from selenium.webdriver.chrome.service import Service
    3) driver = webdriver.Chrome(service=Service("C:\Driver\chromedriver.exe"))
    4) driver.get("https://www.google.com")
    5) driver.close()

    Output:
        


Note:
    The majority of Selenium scripts are consistent across all the Selenium versions, but there may be occasional changes required depending on the specific Selenium version being used.
    For Example:
- To Launch the Web Browser in Selenium 3 the script is:
    from selenium import webdriver

    driver = webdriver.Chrome(execuutable_path="path\to\chromedriver.exe")

- To Launch the Web Browser in Selenium 4 the script is:
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service

    driver = webdriver.Chrome(service = Service("path\to\chromedriver.exe"))

Setup Environment for Python with Selenium



Setup & Configure Web Driver in PyCharm:

Pre-Requirements:
1.  Python
2.  PyCharm
3.  Download browser Specific Drivers.

    Step 1:
- Download and install Python.

    Step 2: 
- Download and install PyCharm

    Step 3 :
- To download Browser-specific divers first, go to the official Selenium website.
- Then go to the Download page.

        

- Scroll down the page to search "+Browsers" Button

        


- Click on that "+Browser" button, and then you will see all the browser-specific drivers' links.

        


- Based on which browser you want to do automation testing that related browser driver you need to download.
- Direct links:


Setup Environment: 
    Step 1: First we need to create Project
- Open "PyCharm"
- Click on the Menu (☰),  Select File in that click on New Project...

        

- or, If you open PyCharm for the First time we will see like this, Here click on New Project. 

        

- Specify the Project name and its location, then click on Create

        

- Then your project will be created.

        


    Step 2: Installing Selenium
        We can install selenium in different ways:
        1) Through GUI
                a) Click on the Menu (☰),  Select File in that click on Settings... (shortcut: Ctrl+Alt+S)
                
                b) Select your Project ("Project: YourProject"), then click on Python Interpreter
                
                c) Click on the "+" button
                
                d) Search for "selenium", then click on Install Package.
                    Note: By default, it installs the latest version. If you want to install the older version of Selenium click on '☑Specify Version' and choose the version in the dropdown list. (If the latest version of Selenium causes the error, install an earlier version of Selenium)

                
                e) Then selenium will be installed in your project.
                


        2) Through Terminal (CLI)
                a) On PyChram, left downside we will see the Terminal symbol, click on that (shortcut: Alt+F12)
                
                b) Terminal, shows the current project location(path), there enter this command "pip install selenium" and then press ENTER. Then it will install latest the version of Selenium in your project. 
                Note: If you want to install an older version for example 'selenium 4.91' the command will be like this: pip install selenium==4.9.1

                
                c) Then it will download the selenium driver to your project.


    Step 3: Browser-Specific Drivers
        1) After downloading browser web drivers, by default the files are in .zip format.
        2) First we need to unzip(Extrat) that file, and then all the extracted files need to store in a separate Folder. So that we can find them easily.

(For example, create a folder with the name 'drivers' in C-drive, and move all the extracted web driver files to this folder)