Operations 11 min read

Master Cross‑Browser Selenium Testing with Python: Practical Code Samples

This article provides a step‑by‑step guide for automating cross‑browser web tests using Selenium with Python, covering fixture setup, CSS and XPath selectors, handling dropdowns, checkboxes, mouse hover actions, tab management, and extracting page source, all illustrated with complete code examples.

FunTester
FunTester
FunTester
Master Cross‑Browser Selenium Testing with Python: Practical Code Samples

Cross‑Browser Test Setup with pytest

To run the same test across multiple browsers (Chrome, Firefox, etc.), define a pytest fixture that parametrizes the browser choice. The fixture creates the appropriate webdriver instance, yields it to the test, and closes it after execution.

''' Import required packages '''
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep

@pytest.fixture(params=["chrome", "firefox"], scope="class")
def driver_init(request):
    if request.param == "chrome":
        # initialize Chrome driver
        pass
    if request.param == "firefox":
        # initialize Firefox driver
        pass
    yield
    # clean up
    driver.close()
    # additional teardown steps can be added here

Using CSS and XPath Locators

Selenium offers several locator strategies. Common methods include: find_elements_by_class_name() – locate elements by CSS class. find_elements() – locate elements using a custom strategy. find_element_by_link_text() – locate a link by its exact text. find_element_by_partial_link_text() – locate a link by a partial match.

Example of using find_element_by_partial_link_text and find_elements_by_class_name:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.example.com")

try:
    element = driver.find_element_by_partial_link_text("START TESTING")
    print("Element found")
    buttons = driver.find_elements_by_class_name('home-btn-2')
    print("Button found")
except NoSuchElementException:
    print("Element not found")

sleep(10)
driver.close()

Capturing Page Source with innerHTML

The innerHTML attribute retrieves the HTML markup of a WebElement. It can be saved to a file for later analysis.

from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.example.com")

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("innerHTML")

with open('page_source.html', 'w') as f:
    f.write(source_code)

sleep(10)
driver.close()

Mouse Hover Actions

To interact with menus that appear on hover, use ActionChains and move_to_element() before clicking the target item.

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.example.com")

action = ActionChains(driver)
parent_menu = driver.find_element_by_id("bs-example-navbar-collapse-1")
action.move_to_element(parent_menu).perform()

child_menu = driver.find_element_by_xpath("//a[contains(text(),'Automation')]")
child_menu.click()

sleep(10)
driver.close()

Closing Tabs vs. Closing the Browser

driver.close()

closes the current tab, while driver.quit() shuts down the entire browser session. To switch between windows, use driver.switch_to.window() with the appropriate handle from driver.window_handles.

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get('https://www.google.com')
# Open a new window
driver.execute_script("window.open('');")
time.sleep(5)
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("https://www.example.com")
time.sleep(5)
# Close the new window
driver.close()
time.sleep(5)
# Switch back to the original window
driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.example.com")
time.sleep(5)
# driver.close()  # optional final close

Handling Dropdown Menus

Use the Select class to interact with <select> elements. Common methods are select_by_index(), select_by_visible_text(), and select_by_value(). First locate the dropdown with find_element_by_xpath(), then apply the desired selection method.

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from time import sleep

driver = webdriver.Firefox()
driver.get("http://demos.example.com/test_Menu.html")

sleep(5)

try:
    select_elem = Select(driver.find_element_by_xpath("//select[@aria-label='select']"))
    select_elem.select_by_visible_text("bleed through")
    sleep(5)
    select_elem.select_by_index(0)
    sleep(5)
except NoSuchElementException:
    print("Element not found")

sleep(5)
driver.quit()

Checkbox Interaction

Locate a checkbox using XPath and click it to toggle its state.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep

driver = webdriver.Firefox()
driver.get("http://demos.example.com/test_CheckBox.html")

sleep(5)

try:
    driver.find_element_by_xpath("//*[contains(text(), 'cb7: normal checkbox')]").click()
except NoSuchElementException:
    print("Element not found")

sleep(5)
driver.quit()

Selecting Elements with CSS Selectors

The find_elements_by_css_selector() method locates elements using standard CSS selector syntax. The example below clicks a login button identified by the li.login selector.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.example.com/")

sleep(5)

try:
    driver.find_element_by_css_selector("li.login").click()
except NoSuchElementException:
    print("Element not found")

sleep(5)
driver.quit()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAutomationtestingSeleniumpytestcross‑browser
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.