How to Use Assertions in Selenium Tests

How to Use Assertions in Selenium Tests

Here's a basic guide to working with links and buttons in Selenium (using Python). Selenium is widely used for automating web applications for testing purposes. Below, you'll find explanations and example code snippets.


🧭 Prerequisites

You need to have:


Python installed


Selenium installed (pip install selenium)


A web driver (like ChromeDriver or GeckoDriver) that matches your browser


πŸš€ Setting Up Selenium

python

Copy

Edit

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.chrome.service import Service

from webdriver_manager.chrome import ChromeDriverManager


# Start Chrome

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.get("https://example.com")  # Replace with your URL

πŸ”— Clicking a Link

By Link Text

python

Copy

Edit

link = driver.find_element(By.LINK_TEXT, "More information...")

link.click()

By Partial Link Text

python

Copy

Edit

partial_link = driver.find_element(By.PARTIAL_LINK_TEXT, "More")

partial_link.click()

πŸ”˜ Clicking a Button

Buttons can be selected using different attributes like ID, name, class, tag, or XPath.


By ID

python

Copy

Edit

button = driver.find_element(By.ID, "submit-button")

button.click()

By Name

python

Copy

Edit

button = driver.find_element(By.NAME, "submit")

button.click()

By Class Name

python

Copy

Edit

button = driver.find_element(By.CLASS_NAME, "btn-primary")

button.click()

By XPath (for more complex selections)

python

Copy

Edit

button = driver.find_element(By.XPATH, "//button[text()='Submit']")

button.click()

✅ Tips

Always wait for elements to be present using WebDriverWait and expected_conditions to avoid timing issues.


You can use find_elements() to get a list of matching elements.


Example with Wait

python

Copy

Edit

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC


wait = WebDriverWait(driver, 10)

button = wait.until(EC.element_to_be_clickable((By.ID, "submit-button")))

button.click()

Learn Selenium JAVA Course in Hyderabad

Read More

Handling Checkboxes and Radio Buttons in Selenium

How to Verify Page Title and URL with Selenium

Visit Our IHUB Talent Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing

A Beginner's Guide to ETL Testing: What You Need to Know