Bird
Raised Fist0
Selenium Pythontesting~15 mins

Browser-specific workarounds in Selenium Python - Build an Automation Script

Choose your learning style10 modes available
Verify login functionality with browser-specific workaround for Chrome
Preconditions (2)
Step 1: Open the login page at 'https://example.com/login'
Step 2: Enter 'testuser' in the username input field with id 'username'
Step 3: Enter 'Test@1234' in the password input field with id 'password'
Step 4: Click the login button with id 'loginBtn'
Step 5: If browser is Chrome, execute JavaScript to remove any overlay blocking clicks
Step 6: Wait until the URL changes to 'https://example.com/dashboard'
Step 7: Verify that the page title contains 'Dashboard'
✅ Expected Result: User is successfully logged in and navigated to the dashboard page with correct title
Automation Requirements - selenium_python
Assertions Needed:
Verify current URL is 'https://example.com/dashboard'
Verify page title contains 'Dashboard'
Best Practices:
Use explicit waits to wait for URL change and element visibility
Detect browser type to apply workaround only for Chrome
Use Page Object Model to separate page interactions
Avoid hardcoded sleeps; use WebDriverWait instead
Automated Solution
Selenium Python
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 EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import platform

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.username_input = (By.ID, 'username')
        self.password_input = (By.ID, 'password')
        self.login_button = (By.ID, 'loginBtn')

    def enter_username(self, username):
        WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located(self.username_input)
        ).clear()
        self.driver.find_element(*self.username_input).send_keys(username)

    def enter_password(self, password):
        WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located(self.password_input)
        ).clear()
        self.driver.find_element(*self.password_input).send_keys(password)

    def click_login(self):
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.login_button)
        ).click()


def test_login_with_chrome_workaround():
    options = Options()
    options.add_argument('--headless=new')  # Use headless mode for faster test
    service = Service()
    driver = webdriver.Chrome(service=service, options=options)

    try:
        driver.get('https://example.com/login')

        login_page = LoginPage(driver)
        login_page.enter_username('testuser')
        login_page.enter_password('Test@1234')

        # Browser-specific workaround for Chrome
        if 'chrome' in driver.capabilities.get('browserName', '').lower():
            # Remove any overlay that blocks clicks using JS
            driver.execute_script("""
                const overlay = document.querySelector('.overlay');
                if (overlay) { overlay.style.display = 'none'; }
            """)

        login_page.click_login()

        # Wait for URL to change to dashboard
        WebDriverWait(driver, 10).until(
            EC.url_to_be('https://example.com/dashboard')
        )

        # Assert URL
        assert driver.current_url == 'https://example.com/dashboard', f"Expected URL to be dashboard but got {driver.current_url}"

        # Assert page title contains 'Dashboard'
        WebDriverWait(driver, 10).until(
            EC.title_contains('Dashboard')
        )
        assert 'Dashboard' in driver.title, f"Expected title to contain 'Dashboard' but got {driver.title}"

    finally:
        driver.quit()

This test script uses Selenium with Python to automate the login process on a website.

We define a LoginPage class to keep selectors and actions organized, following the Page Object Model.

We open the login page, enter username and password, then check if the browser is Chrome by inspecting driver.capabilities. If it is Chrome, we run JavaScript to hide any overlay that might block clicks. This is the browser-specific workaround.

We then click the login button and wait explicitly for the URL to change to the dashboard page and for the page title to contain 'Dashboard'.

Assertions verify the URL and title to confirm successful login.

Explicit waits ensure the test waits only as long as needed, avoiding flaky tests.

Finally, the browser is closed in a finally block to clean up.

Common Mistakes - 4 Pitfalls
Using time.sleep() instead of explicit waits
Not detecting browser type before applying workaround
Using brittle XPath selectors instead of stable IDs or classes
Not cleaning up the browser session after test
Bonus Challenge

Now add data-driven testing with 3 different username and password combinations to verify login success or failure.

Show Hint

Practice

(1/5)
1. Why do we need browser-specific workarounds in Selenium tests?
easy
A. Because different browsers may behave differently and need special handling
B. Because Selenium only supports one browser at a time
C. Because browsers do not support JavaScript
D. Because tests run faster on some browsers

Solution

  1. Step 1: Understand browser differences

    Browsers like Chrome, Firefox, and Edge can behave differently in how they handle web elements or JavaScript.
  2. Step 2: Recognize need for workarounds

    To keep tests reliable, we write special code for each browser to handle these differences.
  3. Final Answer:

    Because different browsers may behave differently and need special handling -> Option A
  4. Quick Check:

    Browser differences = need workarounds [OK]
Hint: Remember: Different browsers act differently, so adjust tests [OK]
Common Mistakes:
  • Thinking Selenium supports only one browser at a time
  • Believing all browsers behave exactly the same
  • Assuming JavaScript is unsupported in browsers
2. Which is the correct way to detect the browser name in Selenium Python?
easy
A. driver.get_browser_name()
B. driver.getCapabilities('browser')
C. driver.browserName
D. driver.capabilities['browserName']

Solution

  1. Step 1: Recall Selenium's capability dictionary

    Selenium stores browser info in driver.capabilities, a dictionary with keys like 'browserName'.
  2. Step 2: Identify correct syntax

    Accessing driver.capabilities['browserName'] returns the browser name string correctly.
  3. Final Answer:

    driver.capabilities['browserName'] -> Option D
  4. Quick Check:

    Use capabilities dictionary for browser name [OK]
Hint: Use driver.capabilities['browserName'] to get browser name [OK]
Common Mistakes:
  • Using non-existent methods like get_browser_name()
  • Trying to access driver.browserName directly
  • Using wrong method names or parameters
3. What will the following code print if the browser is Firefox?
browser = driver.capabilities['browserName']
if browser == 'firefox':
    print('Use Firefox workaround')
else:
    print('Use default code')
medium
A. Use default code
B. Use Firefox workaround
C. KeyError
D. SyntaxError

Solution

  1. Step 1: Check browser value

    The variable browser is assigned driver.capabilities['browserName'], which is 'firefox' here.
  2. Step 2: Evaluate if condition

    Since browser == 'firefox' is True, the code prints 'Use Firefox workaround'.
  3. Final Answer:

    Use Firefox workaround -> Option B
  4. Quick Check:

    Browser is 'firefox' so prints Firefox workaround [OK]
Hint: Match browserName string exactly to choose workaround [OK]
Common Mistakes:
  • Assuming else branch runs for Firefox
  • Confusing case sensitivity in browser name
  • Expecting errors when key exists
4. Identify the error in this Selenium Python snippet for browser-specific workaround:
browser = driver.capabilities.browserName
if browser == 'chrome':
    print('Chrome workaround')
medium
A. driver.capabilities is a dictionary, so .browserName is invalid
B. Missing colon after if statement
C. Print statement syntax is wrong
D. No error, code is correct

Solution

  1. Step 1: Check how capabilities is accessed

    driver.capabilities is a dictionary, so keys must be accessed with ['key'], not dot notation.
  2. Step 2: Identify the error

    Using driver.capabilities.browserName causes an AttributeError because 'dict' has no attribute 'browserName'.
  3. Final Answer:

    driver.capabilities is a dictionary, so .browserName is invalid -> Option A
  4. Quick Check:

    Use ['browserName'] not .browserName [OK]
Hint: Access capabilities keys with brackets, not dot notation [OK]
Common Mistakes:
  • Using dot notation on dictionary objects
  • Ignoring Python syntax for dictionary access
  • Assuming no error in attribute access
5. You want to run a Selenium test that clicks a button differently on Chrome and Firefox due to a known issue. Which code snippet correctly implements this workaround?
hard
A. driver.find_element(By.ID, 'btn').click() # Works on all browsers without changes
B. if driver.capabilities['browserName'] == 'chrome': driver.execute_script("arguments[0].click();", driver.find_element(By.ID, 'btn')) else: driver.find_element(By.ID, 'btn').click()
C. browser = driver.capabilities['browserName'] if browser == 'chrome': driver.find_element(By.ID, 'btn').click() elif browser == 'firefox': driver.execute_script("arguments[0].click();", driver.find_element(By.ID, 'btn'))
D. browser = driver.capabilities.browserName if browser == 'firefox': driver.find_element(By.ID, 'btn').click() else: driver.execute_script("arguments[0].click();", driver.find_element(By.ID, 'btn'))

Solution

  1. Step 1: Detect browser correctly

    Use driver.capabilities['browserName'] to get the browser name safely.
  2. Step 2: Apply browser-specific click

    For Chrome, use normal click(). For Firefox, use JavaScript click workaround to avoid issues.
  3. Final Answer:

    Use if-elif with correct browser detection and click methods -> Option C
  4. Quick Check:

    Detect browser then apply specific click method [OK]
Hint: Detect browser, then choose click method accordingly [OK]
Common Mistakes:
  • Using dot notation on capabilities dictionary
  • Applying wrong click method for browser
  • Assuming one click method fits all browsers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard