How to click on a link in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

We can click on a link on page with the help of locators available in Selenium. Link text and partial link text are the locators generally used for clicking links. Both these locators work with the text available inside the anchor tags.

  • Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.

  • Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.

Example

Coding Implementation with link text

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link with the help of link text locator
driver.find_element_by_link_text("Company").click()
#to close the browser
driver.close()

Coding Implementation with partial link text.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link with the help of partial link text locator
driver.find_element_by_partial_link_text("Privacy").click()
#to close the browser
driver.quit()
raja
Published on 29-Jul-2020 11:12:51
Advertisements