How to execute a Javascript using Selenium in Python?

Rest AssuredDynamic ProgrammingProgramming

We can run Javascript in Selenium webdriver with Python. The Document Object Model communicates with the elements on the page with the help of Javascript. Selenium executes the Javascript commands by taking the help of the execute_script method. The commands to be executed are passed as arguments to the method.

Some operations like scrolling down in a page cannot be performed by Selenium methods directly. This is achieved with the help of the Javascript Executor. The window.scrollTo method is used to perform scrolling operation. The pixels to be scrolled horizontally along the x-axis and pixels to be scrolled vertically along the y-axis are passed as parameters to the method.

Syntax

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

Example

Code Implementation to scroll till page bottom.

driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
# to scroll till page bottom
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")

We can also perform web operations like clicking on a link with Javascript Executor in Selenium. We shall use the execute_script method and pass argument index.click() and webelement to be clicked as arguments to the method.

Syntax

s = driver.find_element_by_css_selector("#id")
driver.execute_script("arguments[0].click();",s)

Example

Code Implementation to perform web operations like click.

Code Implementation to perform web operations like click.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element and then click
s = driver.find_element_by_xpath("//*[text()='Library']")
# perform click with execute_script method
driver.execute_script("arguments[0].click();",s)
print("Page title after click: " + driver.title)

Output

raja
Updated on 22-Nov-2021 10:48:51

Advertisements