As we all know selenium python library provides different methods to perform browser operations like click, sendkeys, gettext etc…
But there is another way to perform these above operations by running java script inside selenium webdriver.
When ever selenium methods don’t work, we can use java script inside the selenium’s webdriver object.
For this selenium provides a method execute_script(script, args)
Run javascript inside browser
Open browser > load url > right click inspect > console & run the java scripts
and the same above script we can run using selenium as
driver.execute_script("return document.getElementById('username')
Now that we have seen how to run java script using selenium webdriver, we will explore some more java script capabilities.
To load specific URL
driver.execute_script("window.location = 'https://qavbox.github.io/demo/'")
Let’s see how we can run the above script
# author - qavalidation.com | youtube.com/qavbox # File - test_javascript.py import time from selenium import webdriver from selenium.webdriver.support.select import Select def test_Sample1(): driver = webdriver.Chrome("/Users/skpatro/sel/chromedriver") # driver.maximize_window() driver.get("https://qavbox.github.io/demo/signup/") driver.implicitly_wait(30) driver.set_page_load_timeout(50) assert "Registration" in driver.title #now load another url using java script driver.execute_script("window.location = 'https://qavbox.github.io/demo/'") time.sleep(3) driver.quit()
To run this above script
pytest -sv test_javascript.py
To get current browser title
print("Title - " + driver.execute_script("return document.title"))
To get current browser url
print("URL - " + driver.execute_script("return document.URL"))
To check if page loaded
print("is Page loaded - " + driver.execute_script("return document.readyState"))
This will return complete
if the page loaded completely,
Identify & click on the element
element = driver.execute_script("return document.querySelector(\"[href='/demo/signup']\")")
driver.execute_script("arguments[0].click();", element)
querySelector
is selenium’s CSS Selector strategy
The same way, we can use getElementById
or even we can identify multiple element matches with getElementsById
SendKeys using javascript
driver.execute_script("return document.getElementById('username').value='qavbox'")
getText or fetching element text
print("Entered value - " + driver.execute_script("return document.getElementById('username').value"))
Check specific radio button or checkbox
driver.execute_script("document.querySelector(\"input[value='seven']\").checked=true")
Scroll on browser screen
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
This above code will scroll till end of page.