Menu Close

How to run JavaScript in Selenium using Python?

Sometimes, we want to run JavaScript in Selenium using Python.

In this article, we’ll look at how to run JavaScript in Selenium using Python.

How to run JavaScript in Selenium using Python?

To run JavaScript in Selenium using Python, we can use the execute_script method.

For instance, we write

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://example.com")
driver.execute_script("document.getElementByElement('foo').click()")

to call driver.get to open the http://example.com page.

Then we call execute_script with "document.getElementByElement('foo').click()" to run "document.getElementByElement('foo').click()".

Conclusion

To run JavaScript in Selenium using Python, we can use the execute_script method.

Posted in Python, Python Answers