0
0
Selenium Pythontesting~15 mins

Find element by link text in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify navigation by clicking a link using link text
Preconditions (2)
Step 1: Locate the link on the page by its exact visible text 'About Us'
Step 2: Click on the 'About Us' link
Step 3: Wait for the new page to load
Step 4: Verify that the current URL is 'https://example.com/about'
✅ Expected Result: The browser navigates to the About Us page with URL 'https://example.com/about'
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the link with text 'About Us' is found and clickable
Verify the browser navigates to the expected URL after clicking
Best Practices:
Use explicit waits to wait for elements to be clickable
Use By.LINK_TEXT locator strategy for finding the link
Use assertions from unittest or pytest for validation
Close the browser after test execution
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
import unittest

class TestLinkTextNavigation(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com')
        self.wait = WebDriverWait(self.driver, 10)

    def test_click_about_us_link(self):
        # Wait until the link with text 'About Us' is clickable
        about_link = self.wait.until(
            EC.element_to_be_clickable((By.LINK_TEXT, 'About Us'))
        )
        about_link.click()

        # Wait until URL changes to expected
        self.wait.until(EC.url_to_be('https://example.com/about'))

        # Assert current URL is correct
        current_url = self.driver.current_url
        self.assertEqual(current_url, 'https://example.com/about')

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

This test script uses Selenium WebDriver with Python's unittest framework.

In setUp, it opens the browser and navigates to the homepage.

The test test_click_about_us_link waits explicitly for the link with exact text 'About Us' to be clickable using By.LINK_TEXT. Then it clicks the link.

It waits until the URL changes to the expected About Us page URL, then asserts the current URL matches.

Finally, tearDown closes the browser to clean up.

This approach ensures the test waits properly for elements and page loads, making it reliable and clear.

Common Mistakes - 4 Pitfalls
Using find_element without explicit wait
Using partial link text instead of exact link text
Not verifying the URL after clicking the link
Not closing the browser after test
Bonus Challenge

Now add data-driven testing to click links with texts 'About Us', 'Contact', and 'Services' and verify their URLs

Show Hint