How can I get a JavaScript variable using Python?

I'm trying to get a Javascript variable using Python and I'm having some problems ...

This is what the variable looks like:

<script type="text/javascript">
var exampleVar = [


After some research I found that its content was in JSON format and I'm new to this ...

My problem is that I would like to get the value of "param3b1" (for example) so that I can use it in my Python program.
How do I do this in Python?


source to share

2 answers

Step by step is what you need to do.

  • extract the json string from the file / html string. you need to get the string between tags first <script>

    and then the variable definition
  • extract the parameter from the json string.

from xml.etree import ElementTree

import json
tree = ElementTree.fromstring(js_String).getroot() #get the root
#use etree.find or whatever to find the text you need in your html file
script_text = tree.text.strip()

#extract json string
#you could use the re module if the string extraction is complex
json_string = script_text.split('var exampleVar =')[1]
#note that this will work only for the example you have given.
    data = json.loads(json_string)
except ValueError:
    print "invalid json", json_string
    value = data['abo']['param3']['param3b1']




You need to use the JSON module.

import json

myJson = json.loads(your_json_string)

param3b1 = myJson['abo']['param3'][1]['param3b1']


JSON module documentation:



All Articles