ClickCease

Selenium Python Programming

1. Setup

Installation:

WebDriver Setup:

from selenium import webdriver
# Set the path to the WebDriver executable
driver = webdriver.Chrome(executable_path='path/to/chromedriver')

2. Basic Commands

3. Locators

4. Interacting with Elements

5. Waits

  • Implicit Wait:
    
    
    driver.implicitly_wait(10) # seconds
  • Explicit Wait:
    
    
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as ECwait = WebDriverWait(driver, 10)
    element = wait.until(EC.visibility_of_element_located((By.ID, "elementId")))

6. Actions

7. Handling Alerts

8. Taking Screenshots


driver.save_screenshot("screenshot.png")

9. Example Test with pytest


import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ECclass TestExample:
@pytest.fixture(scope="class")
def setup(self):
self.driver = webdriver.Chrome(executable_path='path/to/chromedriver')
yield # This allows the test to run
self.driver.quit()def test_example(self, setup):
self.driver.get("https://www.example.com")
assert "Example Domain" in self.driver.title
element = self.driver.find_element(By.CSS_SELECTOR, "h1")
assert element.text == "Example Domain"

10. Tips

  • Browser Compatibility: Ensure the WebDriver version matches the browser version.
  • Headless Mode: Run tests without opening a browser window:
    
    
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    driver = webdriver.Chrome(options=options)
  • Page Object Model: Organize tests for better maintainability.

 

Download Elysium Spark Note

Facebook
X
LinkedIn
Pinterest
WhatsApp