如何使用Python获取JavaScript变量?

5


我正在尝试使用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中实现这个功能?
谢谢!


你可以使用像 https://docs.python.org/3/library/json.html?highlight=json#module-json 这样的模块。 - matsjoyce
1
你考虑过搜索“Python JSON”吗?看一下json - jonrsharpe
如果变量在客户端上,您需要使用ajax或表单提交将其发送回服务器。一旦它在服务器上,使用json编码器/解码器。 - scrappedcola
经过一些研究,我发现那是JSON。不,不,不!JavaScript并不等同于JSON。尽管JSON的语法很大程度上受到了JavaScript对象字面量的启发,但这并不意味着它们是相同的东西。JavaScript是一种编程语言,而JSON则是一种数据格式(类似XML)。 - Felix Kling
2个回答

4

以下是您需要做的步骤。

  1. 从文件/HTML字符串中提取JSON字符串。首先需要获取<script>标签之间的字符串,然后再获取变量定义。
  2. 从JSON字符串中提取参数。

这里有一个演示。

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.
try:
    data = json.loads(json_string)
except ValueError:
    print "invalid json", json_string
else:
    value = data['abo']['param3']['param3b1']

嗨,感谢您提供这个很棒的答案。您有关于如何使用re模块的好链接吗?因为我尝试理解它但是我无法…谢谢! - sylvelk
@Sek8 在你理解re模块之前,你需要先了解正则表达式。http://en.wikipedia.org/wiki/Regular_expression 。然而,如果你要解析的文本足够简单,你应该能够使用split()函数提取JSON对象。 - tom

2

1
非常感谢!我的问题现在是如何从整个<script>var myVar = my_json_string中提取我的JSON字符串...有什么想法吗?我认为我应该使用re模块,但我对它一点也不熟悉。 - sylvelk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接