- Selenium WebDriver and Execute JavaScript
- javascript
- What is JavaScript?
- How to Execute Javascript?
- How to Run Javascript From Python – Detailed Guide?
- Using js2py
- Using requests-html
- Run Javascript File From Python
- Run Javascript Function From Python
- Jupyter Run Javascript From Python
- Conclusion
- You May Also Like
- PyExecJS 1.5.1
- Supported runtimes
- First-class support (runtime class is provided and tested)
- Second-class support (runtime class is privided but not tested)
- Installation
- Details
- License
- Changelog
- 1.5.0
- 1.4.1
- 1.4.0
- 1.3.1
- 1.3.0
- 1.2.0
- 1.1.0
- 1.0.5
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- How to execute a Javascript function in Python with Selenium?
- Syntax
- Example
- Syntax
- Example
Selenium WebDriver and Execute JavaScript
You can execute Javascript with the Selenium WebDriver. In this tutorial you will learn how you can run js directly from your Python code.
You an use selenium to do automated testing of web apps or websites, or just automate the web browser. It can automate both the desktop browser and the mobile browser.
Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want. A webdriver must be installed for selenium to work.
All it takes to execute Javascript is calling the method execute_script(js) where js is your javascript code.
Related course:
javascript
What is JavaScript?
JavaScript is a scripting languages that was made to run on top of websites (client side). It used to be to only make a webpage interactive, but these days there are complete frameworks that let you build the front-end of apps.
How to Execute Javascript?
Before you can use selenium, make sure it is installed and that you also have the right web driver. You can initialize selenium the way you always do.
If you load a website with Python selenium, you can manually inject JavaScript onto that page. If you named your webdriver object driver, then you can execute it like so:
driver.execute_script(«some javascript code here»);
The program below runs a one line javascript command after loading the page. This will show the alert box in the webpage.
from selenium import webdriver
driver=webdriver.Firefox()
driver.implicitly_wait(3)
driver.get(«https://pythonbasics.org»)
js = ‘alert(«Hello World»)’
driver.execute_script(js)
This means you can also use Javascript inside selenium to click on items, like on a button.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get(«http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python»)
driver.execute_script(«document.getElementsByClassName(‘comment-user’)[0].click()»)
To scroll the browser window, you can use Javascript too:
driver.execute_script(«window.scrollTo(0, document.body.scrollHeight);»
But of course, you can also do this the Pythonic way by using the selenium module instead.
Selenium firefox headless
How to Run Javascript From Python – Detailed Guide?
To automate any browser-based activities using Python, you need to run JavaScript from a python program.
You can run javascript from python using js2py.eval_js(“jscode”) code
In this tutorial, you’ll learn the different methods to run JavaScript from Python.
You need to install js2py or requests-html packages to run the JavaScript program from Python. Read the tutorial in detail to understand the installation steps.
If you’re in Hurry
The following code shows how to run JavaScript from Python. The JavaScript function is defined as squareofNum() in a python variable. After that, the eval_js() method is invoked to run the JavaScript function.
import js2py squareofNum = "function f(x) " result = js2py.eval_js(squareofNum) print(result(5))
If You Want to Understand Details, Read on…
There are no inbuilt functions available in Python to execute a JavaScript function. Hence you need to install the libraries js2py or requests-html to execute JavaScript from Python.
Using js2py
js2py is a python package used to translate JavaScript code into python code. It is fully written in Python. Its supports basic JavaScript
This package doesn’t mock any user agent. Hence, you’ll not be able to use the browser capabilities.
Install js2py package using the below code.
To install the package in Jupyter, you can prefix the % symbol in the pip keyword.
Installing js2py
The package is now installed.
Now, you’ll learn how to use this package to execute the JavaScript functions.
Create a JavaScript function that will square the passed number and return it to the calling method. Then invoke the eval_js() method to execute the function below.
import js2py squareofNum = "function f(x) " result = js2py.eval_js(squareofNum) print(result(5))
This is how you can execute basic JavaScript code from Python.
Using requests-html
Requests-html package supports parsing the HTML code. It also mocks a user agent. Hence, you can use this package to execute JavaScript functions that need browser capabilities.
For example, when you are automating functionalities using selenium and during the automation, you may need to get the current URL in Javascript to identify which page is currently loaded in the program. In this case, you can use the requests HTML package to execute a JavaScript program that can identify the current URL.
Install the requests-html package using the below statement.
Installing requests-html
The requests-html package is installed.
Now, you’ll learn how to use the requests-html package to execute a JavaScript package.
First, create html object by initializing it with the HTML constructor as shown below.
Create a JavaScript in a variable called scrpt by enclosing it within the “”” block. The three “”” string is used to create a multiline string in Python.
Then, render the HTML using the html.render() method. You can pass the script=scrpt to the render method.
The render() method will render the HTML code and execute the JavaScript code with a mock user agent like firefox.
from requests_html import HTML html = HTML(html="") scrpt = """ function getURL() < return window.location.href; >""" output = html.render(script=scrpt, reload=False) print(output)
You’ll see the current URL printed in the console.
Run Javascript File From Python
In some cases, you need to store the JavaScript code in a file and execute that script file from python.
Create a JavaScript file with the necessary JavaScript code.
Save the JavaScript code in the same location as python. If you are storing it in another location, then you need to use the appropriate location while executing the below code.
The run_file() method is used to run the JavaScript file from Python.
Pass the JavaScript file name to the run_file() method. It’ll return a tuple that contains python objects equivalent to the JavaScript function.
Using these objects, you can call the function as shown below.
sayHello() is a function defined in the JavaScript file. You can invoke that function using the tempfile object.
Code To Execute the Javascript File
import js2py result, tempfile = js2py.run_file("hello.js"); result= tempfile.sayHello("Stack Vidhya Reader"); print(result);
This is how you can execute a JavaScript file from python.
Run Javascript Function From Python
To run a JavaScript function from python, create a function and assign it into a variable. Then invoke that function using the eval_js() method.
import js2py squareofNum = "function f(x) " result = js2py.eval_js(squareofNum) print(result(5))
Jupyter Run Javascript From Python
You can use the below code to run the JavaScript function from Python.
import js2py squareofNum = "function f(x) " result = js2py.eval_js(squareofNum) print(result(5))
When working with Jupyter, you can only execute basic JavaScript functionalities that don’t require any user agents.
If you execute a script using requests-html in jupyter, you’ll see the below runtime error. Use the editor vscode or Pycharm to execute such programs.
RuntimeError: Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead.
Conclusion
In this tutorial, you’ve learned how to run JavaScript from python.
Also learned how to execute the JavaScript file and javascript function that requires a user agent from Python.
If you’ve any questions, please comment below.
You May Also Like
PyExecJS 1.5.1
This library is no longer maintananced. Bugs are not be fixed (even if they are trivial or essential).
We suggest to use other library or to make a fork.
Run JavaScript code from Python.
PyExecJS is a porting of ExecJS from Ruby. PyExecJS automatically picks the best runtime available to evaluate your JavaScript program.
>>> import execjs >>> execjs.eval("'red yellow blue'.split(' ')") ['red', 'yellow', 'blue'] >>> ctx = execjs.compile(""" . function add(x, y) < . return x + y; . >. """) >>> ctx.call("add", 1, 2) 3
Supported runtimes
First-class support (runtime class is provided and tested)
- PyV8 — A python wrapper for Google V8 engine,
- Node.js
- PhantomJS
- Nashorn — Included with Oracle Java 8
Second-class support (runtime class is privided but not tested)
Installation
Details
If EXECJS_RUNTIME environment variable is specified, PyExecJS pick the JavaScript runtime as a default:
>>> execjs.get().name # this value is depends on your environment. >>> os.environ["EXECJS_RUNTIME"] = "Node" >>> execjs.get().name 'Node.js (V8)'
You can choose JavaScript runtime by execjs.get() :
>>> default = execjs.get() # the automatically picked runtime >>> default.eval("1 + 2") 3 >>> import execjs.runtime_names >>> jscript = execjs.get(execjs.runtime_names.JScript) >>> jscript.eval("1 + 2") 3 >>> import execjs.runtime_names >>> node = execjs.get(execjs.runtime_names.Node) >>> node.eval("1 + 2") 3
The pros of PyExecJS is that you do not need take care of JavaScript environment. Especially, it works in Windows environment without installing extra libraries.
One of cons of PyExecJS is performance. PyExecJS communicate JavaScript runtime by text and it is slow. The other cons is that it does not fully support runtime specific features.
PyV8 might be better choice for some use case.
License
Copyright (c) 2016 Omoto Kenji. Copyright (c) 2011 Sam Stephenson and Josh Peek. (As a author of ExecJS)
Released under the MIT license. See LICENSE for details.
Changelog
1.5.0
1.4.1
- Fixed arguments of module-level functions.
- Fixed bug of execution with pipe.
- Fixed wrong excption is raised.
1.4.0
- Fixed required libraries.
- Fixed order of output of —print-available-runtimes .
- Execute some JavaScript runtime with pipe/stdin (without temporary file).
1.3.1
1.3.0
1.2.0
- Supported Python 3.5
- Supported Nashorn(Java 8 JavaScript engine) as runtime
- Dropped support for Python 2.6 and 3.2
1.1.0
- Supported Python 3.4
- Supported SlimerJS as runtime
- Supported PhantomJS as runtime
- Fixed JScript runtime on Windows 8
1.0.5
- Supported Python 3.3
- Fixed file handle leaking
- Fixed issue with passenger-nginx-4.0
1.0.4
1.0.3
- Javascript sources were embeded in init.py. ‘which’ command were reimplemented by pure python.
1.0.2
1.0.1
1.0.0
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)