How To Click On Javascript Button In Selenium Python

As you navigate through web pages using Selenium in Python, you may encounter buttons that are activated by JavaScript.

These buttons may present a challenge for automated testing, as they may require the execution of the JavaScript code in order to function properly. In this tutorial, we will go through the steps needed to click on a JavaScript button using Selenium in Python.

Step 1: Import necessary libraries

We first need to import the required libraries for this task. We will be using the Selenium WebDriver to control a web browser, and the WebDriverWait module to wait for the button to become clickable.

Step 2: Start a web driver

We will now start a new instance of a web driver. In this tutorial, we will be using Google Chrome, but you can use any browser that is supported by Selenium.

Step 3: Navigate to web page

We will now navigate to the web page that contains the JavaScript button. In this tutorial, we will be using the following web page:

Step 4: Wait for the button to become clickable

We will now wait for the button to become clickable using the WebDriverWait module. This ensures that the button is loaded and ready to be clicked before we attempt to click it.

The number 10 represents the maximum time (in seconds) that the WebDriverWait function will wait before throwing a TimeoutException. The purpose of this code is to wait for an element on a webpage to become clickable before proceeding.

In this example, we are waiting for a button with the class “js-button” to become clickable. You can modify the CSS selector to match the button that you want to click.

Step 5: Click on the button

Now that the button is clickable, we can proceed to click on it using the click() method.

And that’s it! You have successfully clicked on a JavaScript button using Selenium in Python.

Conclusion

JavaScript buttons can be a challenge for automated testing, but with the right tools and techniques, they can be easily clicked using Selenium in Python. By following the steps outlined in this tutorial, you can ensure that your automated tests are able to interact with all types of web elements, including JavaScript buttons.

Full code: