How to execute a Javascript function in Python with Selenium?


We can execute a JavaScript function in Python with Selenium webdriver. DOM interacts with the elements via JavaScript. Selenium is capable of executing JavaScript commands with the execute_script method.

Few actions like web scrolling cannot be done by Selenium directly. For this, we shall use the JavaScript Executor. We shall take the help of the JavaScript command window.scrollTo and pass it to the execute_script method. To scroll to the bottom of the page, we have to pass 0 and document.body.scrollHeight as parameters to the window.scrollTo.

Syntax

driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")

Example

from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\geckodriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
#scroll till page bottom
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);)

We can also do web action like click on a link with JavaScript. Here, also we shall utilize the execute_script method and pass arguments with index and element as parameters to that method.

Syntax

e = driver.find_element_by_css_selector(".cls")
driver.execute_script("arguments[0].click();",e)

Let us click the link Library on the page.

Example

from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\geckodriver.exe")
driver.implicitly_wait(0.8)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element
l = driver.find_element_by_xpath("//*[text()='Library']")
#click with execute_script
driver.execute_script("arguments[0].click();",l)
print("Page title after click: " + driver.title)

Output

Updated on: 01-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements