Click a href button with Selenium and Python?

SeleniumAutomation TestingTesting Tools

We can click a link/button with its href link in Selenium webdriver. This can be achieved by multiple ways. We can use find_element_by_link_text() and find_element_by_partial_link_text() methods to perform this task.

The find_element_by_link_text() method is used to identify an element with the text within the anchor tag as specified in the method parameter . If there is no matching text, NoSuchElementException is thrown.

Syntax

find_element_by_link_text("Coding Ground")

The find_element_by_partial_link_text() method is used to identify an element by partially matching with the text within the anchor tag as specified in the method parameter. If there is no matching text, NoSuchElementException is thrown.

Syntax −

find_element_by_partial_link_text("Coding")

Example

Code Implementation with find_element_by_link_text().

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
# identify element with link text and click()
l=driver.find_element_by_link_text("Privacy Policy")
l.click()
driver.quit()

Example

Code Implementation with find_element_by_partial_link_text().

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
# identify element with partial link text and click()
l=driver.find_element_by_partial_link_text("Privacy")
l.click()
driver.quit()
raja
Published on 28-Aug-2020 13:03:40
Advertisements