如何使用Python检索JavaScript变量?

2024-09-28 20:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文


我试图使用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中执行此操作?
谢谢!


Tags: keytextvartypescriptjavascriptparam1param2
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. 从file/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']

相关问题 更多 >