Running javascript in Selenium using Python.

SeleniumAutomation TestingTesting ToolsJavascriptPython

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 Javascript Executor. The window.scrollTo method is used to perform scrolling operation. The pixels to be scrolled horizontally along x axis and pixels to be scrolled vertically along 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

from selenium import webdriver
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.

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
Published on 26-Oct-2020 10:45:47
Advertisements