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.

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 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