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
Comments
Post a Comment