2014-10-07 66 views
3


我试图用Python检索JavaScript变量,我有一些问题...

这里是可变的样子:如何使用Python检索JavaScript变量?

<script type="text/javascript"> 
var exampleVar = [ 
    {...}, 
    {...}, 
    { 
     "key":"0000", 
     "abo": 
      { 
       "param1":"1" 
       "param2":"2" 
       "param3": 
        [ 
         { 
          "param3a1":"000" 
          "param3a2":"111" 
         }, 
         { 
          "param3b1":"100" 
          "param3b2":"101" 
         } 
        ] 
      } 
] 
</script> 

经过一番研究,我发现,它的内容是JSON格式,我是新手...

我现在的问题是,我想检索“param3b1”(例如)的值在我的Python程序中使用它。
如何在Python中执行此操作?
谢谢!

+0

你可以使用一个模块,如https://docs.python.org/3/library/json.html?highlight=json#module-json – matsjoyce 2014-10-07 16:25:13

+1

您是否考虑搜索“Python JSON”?看看['json'](https://docs.python.org/2/library/json.html)。 – jonrsharpe 2014-10-07 16:25:46

+0

如果变量在客户端上,您需要使用ajax或表单发送回来。一旦它在服务器上使用[json编码器/解码器](https://docs.python.org/2/library/json.html) – scrappedcola 2014-10-07 16:26:29

回答

1

一步一个脚印,这是你需要做什么。

  1. 从文件/ html字符串中提取json字符串。您需要首先获取<script>标记之间的字符串,然后从变量定义
  2. 中提取json字符串中的参数。
从xml.etree进口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. 
try: 
    data = json.loads(json_string) 
except ValueError: 
    print "invalid json", json_string 
else: 
    value = data['abo']['param3']['param3b1'] 
+0

嗨,谢谢你这个很好的答案。你有一个关于如何使用重新模块的好链接,因为我试图低估它,但我不能......谢谢! – Sek8 2014-10-07 17:34:26

+0

@ Sek8在理解re模块之前,您需要了解regex。 http://en.wikipedia.org/wiki/Regular_expression。但是,如果您正在解析的文本足够简单,那么您应该能够使用split()提取JSON对象, – tom 2014-10-07 17:38:41

2

您需要使用JSON模块。

import json 

myJson = json.loads(your_json_string) 

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

JSON模块文档:https://docs.python.org/2/library/json.html

+1

非常感谢!我现在的问题是如何从整个'