Click a particular element in Selenium Python
Hello programmers, in this tutorial, we will see how to click on a particular element using selenium Python.
Selenium is an open-source tool that helps in the automation of web browsers controlled via a program. It has a wide range of tools and libraries required for browser automation.
The major advantage of Selenium over UFT (Unified Functional Testing) or RFT (Rational Functional Tester) is that it requires lesser resources and supports parallel testing which reduces time and increases the efficiency of tests.
Selenium supports multiple programming languages such as Python, Java, Ruby, Perl, Javascript, etc.
Here, we will see a demo on how to use it and the click() method of selenium using Python.
Installation of selenium
Using the command prompt of your system, install selenium for python using the following command.
python -m pip install -U selenium
Clicking on an element using Selenium Python
Before running the code, install the chrome driver.
Extract the .exe file from the zip folder downloaded and copy the location of the file.
Add the file location to your system path.
Below given is the illustration for clicking on an element in a website using selenium python.
#Importing necessary Libraries from selenium import webdriver import time #click action function def seleniumClickAction(): #creating a webdriver object driver = webdriver.Chrome(executable_path = 'C:/path/to/dir/chromedriver.exe') driver.get("https://www.codespeedy.com/") #opening the url ele = driver.find_element_by_link_text("Programming Blog") #finding the element time.sleep(10) ele.click() #clicking on the element time.sleep(30) if __name__ == "__main__": seleniumClickAction() #call the function
Output
The chrome browser is triggered and the following URL is opened. Next, the ‘Programming Blogs’ text page appears.
Explanation
At the start of the file, the ‘seleniumClickAction()’ function is triggered. For doing the automation in the chrome browser, we create a web driver object of the chrome driver. We open the website links using the ‘.get()’ method. Next, we find the element ‘Programming Blog’ on the page, and then using the ‘click()’ method, we go to the subsequent next webpage. For the above task, the ‘selenium’ module has been imported.
Leave a Reply