Selenium is a powerful tool for web automation, and when combined with Python, it becomes an easy-to-use yet efficient framework for automating tasks on web applications. In this tutorial, we will walk you through automating a simple ‘Hello World’ task on Jira Data Center (DC) using Selenium in Python. We will cover how to detect web elements, execute JavaScript code, and even debug your automation script. Let’s dive in!

Prerequisites:

Step 1: Check if Python 3.x is Installed

To verify if Python 3.x is installed, open a terminal or command prompt and type:

python --version

Step 2: Check if Selenium is Installed

To verify if the Selenium WebDriver package for Python is installed, run:

pip show selenium

This command will display details about Selenium if it’s installed. You’ll see the version and location if it’s available.

Step 3: Check if a WebDriver (like ChromeDriver) is Installed and in PATH

The WebDriver (e.g., ChromeDriver, GeckoDriver) should be installed and accessible in your system’s PATH. Here’s how you can check:

For ChromeDriver:

Open a terminal and run:

chromedriver --version

For Other Browsers:

Follow the same process but with the command specific to your browser (e.g., geckodriver --version for Firefox).

Tip: If the WebDriver is downloaded but not in your PATH, you can specify the path directly in your script like this:

from selenium import webdriver

driver = webdriver.Chrome(executable_path='/path/to/chromedriver')

Step 4: Verify Access to Jira DC Instance

To confirm access to your Jira DC instance:

If all checks are successful, you’re ready to start automating with Selenium.

Step 5: Setting Up the Basic Selenium Script

In this section, we will create a basic Selenium script that logs into Jira and performs a "Hello World" operation (for instance, navigating to the Jira dashboard).

Step 6: Create a Python Script

  1. Open a Text Editor: Open your preferred text editor or IDE (like Visual Studio Code, PyCharm, or even Notepad).

  2. Write Your Selenium Script: Here’s an example script that opens a webpage and runs some JavaScript:

from selenium import webdriver
from util.conf import JIRA_SETTINGS
from selenium_ui.jira.pages.pages import Login
from selenium_ui.conftest import print_timing
import random
import time

# Constants
JIRA_URL = f"{JIRA_SETTINGS.server_url}"


@print_timing("selenium_app_custom_action")
def app_specific_action(jira_webdriver, jira_datasets):
    admin_login = JIRA_SETTINGS.admin_login
    admin_password = JIRA_SETTINGS.admin_password

    # To run action as specific user uncomment code bellow.
    # NOTE: If app_specific_action is running as specific user, make sure that app_specific_action is running
    # just before test_2_selenium_z_log_out action
    
    @print_timing("selenium_app_specific_user_login")
    def measure():
        @print_timing("login")
        def app_specific_user_login(username=admin_login, password=admin_password):
            login_page = Login(jira_webdriver)
            login_page.delete_all_cookies()
            login_page.go_to()
            login_page.set_credentials(username=username, password=password)
            if login_page.is_first_login():
                login_page.first_login_setup()
            if login_page.is_first_login_second_page():
                login_page.first_login_second_page_setup()
            login_page.wait_for_page_loaded()
        app_specific_user_login(username=admin_login, password=admin_password)  # Call the function to perform the login
        time.sleep(3)
        # At this point, you're logged into Jira and can automate further interactions
        print("Hello World! You are now logged into Jira DC.")

        @print_timing("selenium_view_issue_page")
        def view_issue():
            issue_key = random.choice(jira_datasets['issues'])[0]
            print(f"Opening issue: {issue_key}")
            jira_webdriver.get(f"{JIRA_URL}/browse/{issue_key}")
            print("Waiting for page to load...")
            time.sleep(3)
        view_issue()
    measure()

You can find the complete script for this tutorial in the Bitbucket repository: Jira Selenium Automation Code

Let's break down the Python script, line by line, to explain what each part does.

Code Explanation :-


from selenium import webdriver

from util.conf import JIRA_SETTINGS

from selenium_ui.jira.pages.pages import Login

from selenium_ui.conftest import print_timing

import random

import time

Constants

JIRA_URL = f"{JIRA_SETTINGS.server_url}"

Main Functionality

@print_timing("selenium_app_custom_action")

def app_specific_action(jira_webdriver, jira_datasets):

admin_login = JIRA_SETTINGS.admin_login
admin_password = JIRA_SETTINGS.admin_password

Nested Functions

User Login

@print_timing("selenium_app_specific_user_login")

def measure():

@print_timing("login")

def app_specific_user_login(username=admin_login, password=admin_password):

login_page = Login(jira_webdriver)

login_page.delete_all_cookies()

login_page.go_to()

login_page.set_credentials(username=username, password=password)

if login_page.is_first_login():
  login_page.first_login_setup()
if login_page.is_first_login_second_page():
  login_page.first_login_second_page_setup()

login_page.wait_for_page_loaded()

app_specific_user_login(username=admin_login, password=admin_password) 

time.sleep(3)

print("Hello World! You are now logged into Jira DC.")

View Issue

@print_timing("selenium_view_issue_page")

def view_issue():

issue_key = random.choice(jira_datasets['issues'])[0]

print(f"Opening issue: {issue_key}")

jira_webdriver.get(f"{JIRA_URL}/browse/{issue_key}")

print("Waiting for page to load...")

time.sleep(3)

view_issue()


Execution Order

measure()

Step 7: Detecting Web Elements in Selenium

Selenium provides various ways to detect and interact with web elements. These methods are crucial for automating any web-based tasks. Here’s a breakdown of the commonly used element detection strategies:

  1. By ID:

    driver.find_element_by_id("element_id")

  2. By Name:

    driver.find_element_by_name("element_name")

  3. By XPath:

    driver.find_element_by_xpath("//input[@name='q']")

  4. By Class Name:

    driver.find_element_by_class_name("class_name")

  5. By CSS Selector:

    driver.find_element_by_css_selector("div.classname > input")

For example, if you need to click on the Jira dashboard menu item, you might use something like:

dashboard_menu = driver.find_element_by_id("home_link")
dashboard_menu.click()

Step 8: Running JavaScript in Selenium

Sometimes, Selenium doesn’t directly support certain actions, and this is where executing JavaScript can be useful. You can run JavaScript code using the execute_script method.

For example, scrolling the page to a certain element:

element = driver.find_element_by_id("some_element_id")
driver.execute_script("arguments[0].scrollIntoView(true);", element)

Or executing a custom JavaScript function:

driver.execute_script("alert('Hello from Selenium!');")

Step 9: Handling Delays and Waits

Automation can fail if the script interacts with elements before they fully load. There are two main ways to handle these delays:

  1. Explicit Waits: Wait until a specific condition is met before proceeding.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "element_id"))
)

  1. Implicit Waits: Define a default wait time for all elements.

    driver.implicitly_wait(10)

Step 10: Debugging Selenium Scripts

Debugging Selenium scripts can be tricky, but there are a few strategies you can use to make the process easier:

  1. Use print() Statements: Print intermediate results to track where the script is failing.

print("Attempting to find login button...")

  1. Pause the Script: You can manually pause the script at any point to inspect the web page or element status.

    input("Press Enter to continue...")

  2. Screenshot on Failure: Capture a screenshot if an exception occurs.

    driver.save_screenshot('error.png')

  3. Logging: Use Python’s logging library to track events with more granularity.

    import logging
    logging.basicConfig(level=logging.DEBUG)

Step 11: Closing the WebDriver

Once your script has completed its task, you should always ensure that the browser closes properly:

driver.quit()

This releases the WebDriver resources and closes the browser.

Step 12: Output

image-20241115-103730.png

image-20241115-103629.png

Conclusion

You’ve just created a simple Selenium automation script using Python to log in to Jira DC, run a "Hello World" action, and handle various other operations like detecting elements, running JavaScript, and debugging. With this foundational knowledge, you can automate a wide range of tasks in Jira or any other web-based system.