Contents
Click a Link in Selenium
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
In the following examples, we shall consider loading the HTML file at path https://pythonexamples.org/tmp/selenium/index-31.html . The contents of this HTML file is given below.
<html>
<body>
<p>Hello World!</p>
<a id="about_link" href="/tmp/selenium/index-31-about.html">About Hello World</a>
<br>
<p>New Article</p>
<a id="new_article" href="/tmp/selenium/index-31-new-article.html">About New Article</a>
</body>
</html>
Copy 1. Click on a link element based on id
In the following program, we will find the link element whose id is "about_link", and click on that link element using Element.click() method.
Python Program (Selenium)
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time
# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-31.html')
# Find element by id
myLink = driver.find_element(By.ID, 'about_link')
# Optional
time.sleep(3)
# Click on link
myLink.click()
# Optional
time.sleep(3)
# Close the browser
driver.quit()
2. Click on a link element based on link text
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 import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time
# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-31.html')
# Find element by id
myLink = driver.find_element(By.PARTIAL_LINK_TEXT, 'New Article')
# Optional
time.sleep(3)
# Click on link
myLink.click()
# Optional
time.sleep(3)
# Close the browser
driver.quit()
Summary
In this Python Selenium tutorial, we learned how to click on an HTML link element in webpage, using Element.click() method in Selenium.