【问题标题】:How can I retrieve a JavaScript variable using Python? [closed]如何使用 Python 检索 JavaScript 变量? [关闭]
【发布时间】:2014-12-02 03:44:41
【问题描述】:


我正在尝试使用 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 中做到这一点?
谢谢!

【问题讨论】:

  • 您是否考虑过搜索“Python JSON”?看看json
  • 如果变量在客户端,您需要使用 ajax 或表单帖子将其发回。一旦它在服务器上使用json encoder/decoder
  • “经过一番研究,我发现它是 JSON,” 不,不,不! JavaScript 不是 JSON。 JSON 和 JavaScript 对象字面量具有非常相似的语法(毕竟 JSON 是受该语法启发的),但这并不能使它们成为一回事。 JavaScript 是一种编程语言,JSON 是数据格式(类似于 XML)。

标签: javascript python json


【解决方案1】:

一步一步这是你需要做的。

  1. 从文件/html 字符串中提取 json 字符串。需要先获取&lt;script&gt;标签之间的字符串,再获取变量定义
  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 模块的好链接,因为我试图理解它,但我不能......谢谢!
  • @Sek8 你需要先了解正则表达式才能了解 re 模块。 en.wikipedia.org/wiki/Regular_expression 。但是,如果您要解析的文本足够简单,您应该能够使用 split() 提取 JSON 对象
【解决方案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

【讨论】:

  • 非常感谢!我现在的问题是如何从整个&lt;script&gt;var myVar = my_json_string 中提取我的JSON 字符串......对此有什么想法吗?我想我应该使用re 模块,但我一点也不熟悉。
猜你喜欢
  • 1970-01-01
  • 2013-01-30
  • 2014-04-19
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 2012-10-02
  • 2013-03-04
  • 2015-02-03
相关资源
最近更新 更多