Python Selenium – Find Button by text
In this article, let’s discuss how to find a button by text using selenium. See the below example to get an idea about the meaning of the finding button by text.
We need to find the “CLICK ME!” button using the text “Click me!”.
Selenium: The selenium package is used to automate web browser interaction from Python. It is an open-source tool primarily used for testing. Run the following command in the terminal to install this library:
pip install selenium
Setup Web Drivers:
Web Driver is a package to interact with a Web Browser. You can install any Web Driver according to your browser choice. Install any one of them using the given links-
Here, we are going to use ChromeDriver.
Find xpath of the button:
- Method 1: Using Inspect Element
Right Click on the element you are trying to find the xpath. Select the “Inspect” option.
- Right click on the highlighted area on the console. Go to Copy xpath
- Method 2: Using Chrome Extension to find xpath easily:
We can easily find xpath of an element using a Chrome extension like SelectorGadget.
- Import Selenium and time library
- Set the Web Driver path with the location where you have downloaded the WebDriver
- Call driver.get() function to navigate to a particular URL.
- Call time.sleep() function to wait for the driver to completely load the webpage.
- Use driver.find_element_by_xpath() method to find the button using xpath.
- Finding button by text-
(i) Using normalize-space() method:
(ii) Using text() method:
Note: It is recommended to use normalize-space() method because it trim the left and right side spaces. It is possible that there can be spaces present at the start or at the end of the target text.
- Lastly close the driver using driver.close() function.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!