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.

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.

Snippet

import js2py

squareofNum = "function f(x) {return x*x;}"

result = js2py.eval_js(squareofNum)

print(result(5))

Output

25

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 PythonMonkey

pythonmonkey is a Python package used to execute JavaScript code from Python code. It utilizes the Mozilla SpiderMonkey JavaScript engine for executing JavaScript and WebAssembly. As a result, it supports the entire JavaScript spec and will remain up to date as the language changes.

This package doesn’t mock any user agent. Hence, you’ll not be able to use the browser’s capabilities.

Install pythonmonkey the package using the below code.

To install the package in Jupyter, you can prefix the % symbol in the pip keyword.

Installing js2py

pip install pythonmonkey

The package is now installed.

Now, you’ll learn how to use this package to execute the JavaScript functions.

Example
Before getting into the details, let’s use PythonMonkey to execute some JavaScript code in Python. We’ll just do this in the Python REPL by typing python3 into the console. Then we’ll type the following code and see it executed:

>>> import pythonmonkey as pm
>>> hello = pm.eval(" 'Hello World'.toUpperCase(); ")
>>> print(hello)
'HELLO WORLD'

Loading a JavaScript Module in Python Example
In this example, we’ll have two files: my-javascript-module.js and main.py which imports the functions from the JavaScript code:

// my-javascript-module.js
exports.sayHello = () => {
    console.log('hello, world')
};
# main.py
import pythonmonkey as pm
test = pm.require('./my-javascript-module');
test.sayHello() # this prints hello, world

Output

hello, world

Advanced Example (using WASM in Python)
PythonMonkey can be used to execute WebAssembly in Python!

We’ll read a WebAssembly .wasm file in Python and load it using pythonmonkey.WebAssembly which has a function “factorial()“:

import asyncio # we'll use asyncio to deal with an event loop
import pythonmonkey

# we'll put our code in an async python function
async def async_fn():
  # read the factorial.wasm binary file
  file = open('factorial.wasm', 'rb')
  wasm_bytes = bytearray(file.read())

  # instantiate the WebAssembly code
  wasm_fact = await pythonmonkey.WebAssembly.instantiate(wasm_bytes, {})

  # return the "fac" factorial function from the wasm module
  return wasm_fact.instance.exports.fac;

# await the promise which returns the factorial WebAssembly function
factorial = asyncio.run(async_fn())

# execute WebAssembly code in Python!
print(factorial(4)) # this outputs "24.0" since factorial(4) == 24
print(factorial(5)) # this outputs "120.0"
print(factorial(6)) # this outputs "720.0"

Output:

24.0
120.0
720.0

For more advanced examples, check out this article on Executing Rust in Python using WebAssembly & PythonMonkey or Calling C functions in Python using WebAssembly.

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

pip install 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.

Code

import js2py

squareofNum = "function f(x) {return x*x;}"

result = js2py.eval_js(squareofNum)

print(result(5))

Output

25

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

pip install 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.

Code

from requests_html import HTML

html = HTML(html="<a href='http://www.example.com/'>")

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.

JS File

hello.js

function sayHello(Name) { 
    return "Hello, "+Name+"!";
}

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.

Code

import js2py

squareofNum = "function f(x) {return x*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.

Code

import js2py

squareofNum = "function f(x) {return x*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

Leave a Comment