How to click a link using Selenium?

Click a Link

To click on a specific link in the webpage using Selenium in Python, get the link element, and then call the click() method on the link element object.

linkElement.click()

click() method scrolls to the element, and performs a click action at the center of the element.

Examples

Click on a link element based on id

Consider the below HTML document.

index.html

<html>
 <body>
  <p>Hello World!</p>
  <a id="aboutLink" href="/about.html">About Hello World</a>
  <br>
  <p>New Article</p>
  <a href="/new-article.html">About New Article</a>
 </body>
</html>

In the following program, we will find the link element whose id is "aboutLink", and click on that link element using Element.click() method.

Python Program (Selenium)

from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By

service = Service(executable_path="C:/chromedriver")
#initialize web driver
with webdriver.Chrome(service=service) as driver:
    #navigate to the url
    driver.get('http://127.0.0.1:5500/index.html')
    #find element by id
    myLink = driver.find_element(By.ID, 'aboutLink')
    myLink.click()

Click on a link element based on link text

Consider the below HTML document.

index.html

<html>
 <body>
  <p>Hello World!</p>
  <a id="aboutLink" href="/about.html">About Hello World</a>
  <br>
  <p>New Article</p>
  <a href="/new-article.html">About New Article</a>
 </body>
</html>

In the following program, we will find the link element whose link text contains "New Article", and click on that link element using Element.click() method.

Python Program (Selenium)

from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By

service = Service(executable_path="C:/chromedriver")
#initialize web driver
with webdriver.Chrome(service=service) as driver:
    #navigate to the url
    driver.get('http://127.0.0.1:5500/index.html')
    #find element by partial link text
    myLink = driver.find_element(By.PARTIAL_LINK_TEXT, 'New Article')
    myLink.click()

Summary

In this tutorial of Python Examples, we learned how to click on an HTML link element in webpage, using Element.click() method in Selenium.