Not as familiar on the python side of things, but in general to "port" data across languages (e.g., mixed backends, microservices, etc.), you would use the JSON itself as the intermediate/serialized form of the data. Couldn't you just pass the JSON data directly to JavaScript and then parse it and process from there? (e.g., setup up an endpoint in Python and consume it in JS via JSON.parse() method, or simply export the JSON data to a JSON file and import it in JS) Answer from awp_throwaway on reddit.com
🌐
Reddit
reddit.com › r/webdev › is it possible to pass data from a python file to a javascript file without using flask?
r/webdev on Reddit: Is it possible to pass data from a python file to a javascript file without using flask?
July 27, 2022 -

I'm in an internship where (for whatever reason) the codebase for this internal analytics website does not use a standard framework like flask or django. Instead, someone created their own HTMLReporterclass with its own methods like render_html. I don't really care about this, but one of the things I've been trying to do (for way too long) is make a bar chart and display it on the webpage. The data from the bar chart is returned by a python file where some data wrangling happens.

At first, I just made a plot in python, saved the image, and then embedded it in the html but this didn't work for more complex images, and some of the axis labels were cut off. So I've been trying to pass the data for the barplot to a javascript file that renders a barplot and I'm completely lost at this point.

With a framework like Flask - I could've done something like render_template(..., ..., data=data) and use jinja2 inside a <script> to get it done. But this custom class doesn't have that functionality.

  • I tried using the json-script template tag as described here but that just gives me this error:

... {{ barplot_data|json_script:"plot-data" }}
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got ':'
  • I also tried using a python package like plotly or dash, but they seem to require me to host the plot on a public website before embedding it into html and I can't do that since the data used here is sensitive.

  • I'm right now trying to parse the json file with the javascript itself. I'm running into a bunch of incorrect-path issues, and trying to resolve them.

I'm just thinking that there's gotta be an easier way to do this... right?

Top answer
1 of 4
3
Not as familiar on the python side of things, but in general to "port" data across languages (e.g., mixed backends, microservices, etc.), you would use the JSON itself as the intermediate/serialized form of the data. Couldn't you just pass the JSON data directly to JavaScript and then parse it and process from there? (e.g., setup up an endpoint in Python and consume it in JS via JSON.parse() method, or simply export the JSON data to a JSON file and import it in JS)
2 of 4
2
You can pass serialized data between two languages pretty easily so long as the serialization method is understood between both languages. In this case JSON would probably be the easiest because both Python and JS support JSON serialization and deserialization natively. We then need to decide how we send and receive the serialized data. This can be done through an endpoint on a server, through the local file system or through a child process. Since we don't want to use flask (or another equivalent) we can rule out an endpoint on a server. The next easiest option would be simply writing the JSON data to the local file system in Python. Then consuming that data in JS (assuming you're using a runtime that can access the local file system ie node, deno, bun etc). Finally if you really need true communication between a Python process and a Node process you can spawn a child process in Node, execute the Python script in that child process, have the Python process emit the serialized data through stdout, then collect the chunked data in Node, deseralize the data then continue on working with the data in Node. It should be noted that you can flip this as well, as in Python spins up your Node script in a child process and sends the data to a Node process through stdin. Using the file system is way easier so if you don't need the two processes to communicate at runtime, that would be the ideal way to handle sharing data between the two.
🌐
Ouseful Info
blog.ouseful.info › 2020 › 02 › 02 › grabbing-javascript-objects-out-of-web-pages-and-into-python
Grabbing Javascript Objects Out of Web Pages And Into Python
February 2, 2020 - The recipe is essentially as follows: load in a web page from a Python script into a headless web-browser using selenium; find an off-the-shelf Javascript script to handle circular references in a Javascript object; shove the Javascript script ...
Discussions

Extracting data from javascript var inside <script> with python - Stack Overflow
I'm new with python, BeautifulSoup and other but I want to extract json data which are inside a javascript variable in the "script" tag of a web site. Here is my code for now : import re from bs4 More on stackoverflow.com
🌐 stackoverflow.com
javascript - How get data stored in vars from a js file in python - Stack Overflow
I have a js file that I need to get data out of but I am not sure how to get the data out in the way I want. I would like it to be readable and subscriptable like a python dict(like dict["key/... More on stackoverflow.com
🌐 stackoverflow.com
Can I get data from JavaScript to Python? - Stack Overflow
There is a module that's only available for JS, but my project is written in Python and it will be impossible to transfer it to JS at this point. Is there a way to transfer the data from JS without More on stackoverflow.com
🌐 stackoverflow.com
How can I scrape a page with dynamic content (created by JavaScript) in Python? - Stack Overflow
This example is contrived; the ... from looking at the static markup because it could be dynamically assembled, minified and buried under dozens of other requests and endpoints. The network request will also show any relevant request payload details like access token you may need. After obtaining the endpoint URL and relevant details, build a request in Python using a standard HTTP library and request the data: >>> import requests >>> res = requests.get("https://... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
9
>>> import json
>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> x = json.loads(weird_json)
>>> x
{u'x': 3}
>>> y = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> y
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

You can take the HTML data, and convert it into a dictionary, enabling you to do: print x['x']

This is the starting point, create a socket in Python which listens to a port. Then have it recieve data.

In Javascript, open a socket which can connect to a port (the one Python listens to). Use, say: http://socket.io/

This is a pure socket-to-socket related issue?


A working relationship between Python and Javascript (on port 80):

from socket import *
import json
s = socket()
s.bind(('', 80))
s.listen(4)
ns, na = s.accept()

while 1:
    try:
        data = ns.recv(8192)
    except:
        ns.close()
        s.close()
        break

    data = json.loads(data)
    print data

There you got a socket listening to 80, connect to that and send whatever you want.

function callPython()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","Form-data",true);
xmlhttp.send();
}

For instance, where you can send the form data as a string, replacing "Form-data" and the response from Python can be put into "myDiv" :)

2 of 2
2

Something like Ghost.py should be able to do what you want.

This allows evaluation of JavaScript.

result, resources = ghost.evaluate(
    "document.getElementById('my-input').getAttribute('value');")

Which should help.

I've used PhantomJS the JS headless webkit browser and this is a port and/or reworking of that using Python.


In my use case I just called PhantomJS from subprocess.call as I couldn't be bothered to install the Ghost dependencies.

I just emitted JSon to stdout and json.loads on it.

🌐
Theautomatic
theautomatic.net › home › scraping data from a javascript webpage with python
Scraping data from a JavaScript webpage with Python - Open Source Automation
May 4, 2020 - Now, let’s use requests_html to run the JavaScript code in order to render the HTML we’re looking for. # import HTMLSession from requests_html from requests_html import HTMLSession # create an HTML Session object session = HTMLSession() # Use the object above to connect to needed webpage resp = session.get("https://finance.yahoo.com/quote/NFLX/options?p=NFLX") # Run JavaScript code on webpage resp.html.render()
🌐
Python Programming
pythonprogramming.net › javascript-dynamic-scraping-parsing-beautiful-soup-tutorial
Scraping Dynamic Javascript Text
If we don't do that, we're not going to get the data we want, it'll just be an empty page. Otherwise, we're using the PyQt Webkit to mimic a browser. Upon having done that, we can see the javascript data! Look at you shinin! ... import dryscrape sess = dryscrape.Session() sess.visit('https://pythonprogramming.net/parsememcparseface/') source = sess.body() soup = bs.BeautifulSoup(source,'lxml') js_test = soup.find('p', class_='jstest') print(js_test.text)
🌐
MakeUseOf
makeuseof.com › home › programming › how to get python and javascript to communicate using json
How to Get Python and JavaScript to Communicate Using JSON
February 12, 2022 - Typically, in such communication, a backend technology (API provider) responds with data after receiving a request from a front-end script. There are many request types, though; in this article, you'll learn how to use the POST request to send JSON format data from JavaScript to the server using a Python API.
Find elsewhere
🌐
ZenRows
zenrows.com › homepage › tutorial › scraping javascript-rendered web pages with python: complete guide
Scraping JavaScript-Rendered Web Pages With Python: Complete Guide - ZenRows
September 10, 2024 - Let's create a web scraper using Selenium to extract data from JavaScript-rendered pages. We'll scrape the JS Rendering demo page from the ScrapingCourse website. At first, the website renders a template page on the server; then, JavaScript populates it on the client's side. ... Before we start building our scraper, let's set up the necessary tools. We'll be using Selenium with Python...
🌐
Scrape.do
scrape.do › home › blog › 6 ways to scrape a javascript-rendered web page in python
6 Ways to Scrape A JavaScript-Rendered Web Page in Python | Scrape.do
July 14, 2025 - Master scraping dynamic content from JavaScript-heavy websites using Python with different methods, ranked from simplest to most advanced.
🌐
Andrew Healey
healeycodes.com › talking-between-languages
Talking to Python from JavaScript (and Back Again!) — Andrew Healey
April 11, 2019 - // GET is the default method, so we don't need to set it ... Awesome! We've got Python talking to client-side JavaScript using JSON for data serialization. Let's flip it and send JSON to Python from the browser.
🌐
Plain English
python.plainenglish.io › scraping-javascript-rendered-content-using-python-and-apis-f82f3f3d7c19
Scraping JavaScript-Rendered Content Using Python and APIs | Python in Plain English
February 3, 2025 - To get started, you’ll need to install Selenium and a browser driver (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox). ... Once you have everything installed, you can use the following Python script to scrape JavaScript-rendered content: from selenium import webdriver from selenium.webdriver.common.by import By import time # Set up WebDriver driver = webdriver.Chrome(executable_path='/path/to/chromedriver') # Open the webpage driver.get('https://example.com') # Wait for the page to fully load (if necessary) time.sleep(5) # Retrieve the dynamically rendered content content = driver.find_element(By.ID, 'content').text print(content) # Close the WebDriver driver.quit()
🌐
ScraperAPI
scraperapi.com › home › blog › how to build a javascript table web scraper with python in 5 steps
How To Build A JavaScript Table Web Scraper With Python in 5 Steps
March 31, 2026 - Yes, we just said that we can’t access a JavaScript table by just requesting the HTML file, but that’s not what we’re going to do. If you’ve read carefully, you know by know that dynamic tables need to pull the data from somewhere, so if we can imitate the request the browser sends when rendering the page, we can access the exact same data without the need of a headless browser. For this tutorial, we’ll scrape https://datatables.net/examples/data_sources/ajax.html using Python’s Requests library to extract all employee data displayed on the site.
🌐
Medium
megandibble.medium.com › web-scraping-a-javascript-heavy-website-in-python-and-using-pandas-for-analysis-7efb22315858
Web Scraping a Javascript Heavy Website in Python and Using Pandas for Analysis
October 11, 2021 - import requestsurl = ‘https://wem.americasmart.com/api/v1.2/Search/LinesAndPhotosByMarket?status=ACTIVE_AND_UPCOMING&marketID=23' r = requests.get(url) info = r.json() ... Sr. Content Manager @ Alteryx. I mostly write about data science and career advice. Occasionally I’m funny.
Top answer
1 of 16
249

EDIT Sept 2021: phantomjs isn't maintained any more, either

EDIT 30/Dec/2017: This answer appears in top results of Google searches, so I decided to update it. The old answer is still at the end.

dryscape isn't maintained anymore and the library dryscape developers recommend is Python 2 only. I have found using Selenium's python library with Phantom JS as a web driver fast enough and easy to get the work done.

Once you have installed Phantom JS, make sure the phantomjs binary is available in the current path:

phantomjs --version
# result:
2.1.1

Example

To give an example, I created a sample page with following HTML code. (link):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Javascript scraping test</title>
</head>
<body>
  <p id='intro-text'>No javascript support</p>
  <script>
     document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript';
  </script> 
</body>
</html>

without javascript it says: No javascript support and with javascript: Yay! Supports javascript

Scraping without JS support:

import requests
from bs4 import BeautifulSoup
response = requests.get(my_url)
soup = BeautifulSoup(response.text)
soup.find(id="intro-text")
# Result:
<p id="intro-text">No javascript support</p>

Scraping with JS support:

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(my_url)
p_element = driver.find_element_by_id(id_='intro-text')
print(p_element.text)
# result:
'Yay! Supports javascript'

You can also use Python library dryscrape to scrape javascript driven websites.

Scraping with JS support:

import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit(my_url)
response = session.body()
soup = BeautifulSoup(response)
soup.find(id="intro-text")
# Result:
<p id="intro-text">Yay! Supports javascript</p>
2 of 16
128

We are not getting the correct results because any javascript generated content needs to be rendered on the DOM. When we fetch an HTML page, we fetch the initial, unmodified by javascript, DOM.

Therefore we need to render the javascript content before we crawl the page.

As selenium is already mentioned many times in this thread (and how slow it gets sometimes was mentioned also), I will list two other possible solutions.


Solution 1: This is a very nice tutorial on how to use Scrapy to crawl javascript generated content and we are going to follow just that.

What we will need:

  1. Docker installed in our machine. This is a plus over other solutions until this point, as it utilizes an OS-independent platform.

  2. Install Splash following the instruction listed for our corresponding OS.
    Quoting from splash documentation:

    Splash is a javascript rendering service. It’s a lightweight web browser with an HTTP API, implemented in Python 3 using Twisted and QT5.

    Essentially we are going to use Splash to render Javascript generated content.

  3. Run the splash server: sudo docker run -p 8050:8050 scrapinghub/splash.

  4. Install the scrapy-splash plugin: pip install scrapy-splash

  5. Assuming that we already have a Scrapy project created (if not, let's make one), we will follow the guide and update the settings.py:

    Then go to your scrapy project’s settings.py and set these middlewares:

    DOWNLOADER_MIDDLEWARES = {
          'scrapy_splash.SplashCookiesMiddleware': 723,
          'scrapy_splash.SplashMiddleware': 725,
          'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
    }
    

    The URL of the Splash server(if you’re using Win or OSX this should be the URL of the docker machine: How to get a Docker container's IP address from the host?):

    SPLASH_URL = 'http://localhost:8050'
    

    And finally you need to set these values too:

    DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
    HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
    
  6. Finally, we can use a SplashRequest:

    In a normal spider you have Request objects which you can use to open URLs. If the page you want to open contains JS generated data you have to use SplashRequest(or SplashFormRequest) to render the page. Here’s a simple example:

    class MySpider(scrapy.Spider):
        name = "jsscraper"
        start_urls = ["http://quotes.toscrape.com/js/"]
    
        def start_requests(self):
            for url in self.start_urls:
            yield SplashRequest(
                url=url, callback=self.parse, endpoint='render.html'
            )
    
        def parse(self, response):
            for q in response.css("div.quote"):
            quote = QuoteItem()
            quote["author"] = q.css(".author::text").extract_first()
            quote["quote"] = q.css(".text::text").extract_first()
            yield quote
    

    SplashRequest renders the URL as html and returns the response which you can use in the callback(parse) method.


Solution 2: Let's call this experimental at the moment (May 2018)...
This solution is for Python's version 3.6 only (at the moment).

Do you know the requests module (well who doesn't)?
Now it has a web crawling little sibling: requests-HTML:

This library intends to make parsing HTML (e.g. scraping the web) as simple and intuitive as possible.

  1. Install requests-html: pipenv install requests-html

  2. Make a request to the page's url:

    from requests_html import HTMLSession
    
    session = HTMLSession()
    r = session.get(a_page_url)
    
  3. Render the response to get the Javascript generated bits:

    r.html.render()
    

Finally, the module seems to offer scraping capabilities.
Alternatively, we can try the well-documented way of using BeautifulSoup with the r.html object we just rendered.

🌐
Streamlit
discuss.streamlit.io › using streamlit
Passing Data Back From JavaScript to Python - Using Streamlit - Streamlit
December 18, 2024 - I need to pass information back from JavaScript to Python. Is there a way to do this. After looking through forums and googling, I haven’t found an answer yet. What I really want is to call a python function, run some…
🌐
Reddit
reddit.com › r/webscraping › how to extract variable from .js file using python?
r/webscraping on Reddit: How to extract variable from .js file using python?
September 28, 2025 -

Hi all, I need to extract a specific value embedded inside a large JS file served from a CDN. The file is not JSON; it contains a JS object literal like this (sanitized):

var Ii = {
  'strict': [
    { 'name': 'randoje', 'domain': 'example.com', 'value': 'abc%3dXYZ...' },
    ...
  ],
  ...
};

Right now I could only think of using a regex to grab the value 'abc%3dXYZ...'.
But i am not that familliar with regex and I cant wonder but think that there is an easier way of doing this.

any advice is appreciated a lot!