python使用execjs库获取js文件return的json数据,弹出的解码问题如何解决?

提问python使用execjs库获取js文件return的json数据,弹出的解码问题如何解决?

img

img

看了下execjs源代码和js代码,由于函数get_data内部调用了异步的ajax方法,没有返回值ajax的值,而题注是通过输出2次结果来给execjs读取控制台内容后得到返回的内容,这个是json对象,包含多个属性,所以_extract_result无法unpack结果

        def _extract_result(self, output):
            output = output.replace("\r\n", "\n").replace("\r", "\n")
            output_last_line = output.split("\n")[-2]
    
            ret = json.loads(output_last_line)
            ###print(ret)##ret是js console.log打印出的数据,这个json有多个属性,所以下面的status, value = ret是无法unpack的,变量不够
            if len(ret) == 1:
                ret = [ret[0], None]
            status, value = ret

            if status == "ok":
                return value
            else:
                raise ProgramError(value)

更改下zgg函数如下,符合execjs需要的结果

function zgg(n) {
    i = Vm.parse(n.lastFetchTime + "000")
      , a = Vm.parse(n.lastFetchTime + "000")
      , r = n.data
      , s = zie.decrypt(r.toString(), i, {
        iv: a
    })
        , c = s.toString(Vm);
    console.log(JSON.stringify(['ok',c]));
    return c
}

python代码

import subprocess
from functools import partial #用来固定某个参数的固定值
subprocess.Popen=partial(subprocess.Popen,encoding='utf-8')


import execjs
import json
cell=execjs.compile(open('纠错.js',encoding='utf-8').read())
result=cell.call('get_data')##注意result为字符串
result=json.loads(result)

print(result)

其实直接用python自己实现js crypto的aes解密就行了,根本不需要execjs,还得安装node js。

在使用execjs库获取JS文件的返回值时,可能会遇到解码问题。这可能是因为JS文件返回的数据使用了一些非标准的字符编码,或者使用了不同于Python默认的字符编码。

为了解决这个问题,可以尝试使用Python的chardet库来检测返回数据的编码类型。例如:

import execjs
import chardet

# 加载JS文件
with open('example.js', 'r', encoding='utf-8') as f:
    js_code = f.read()

# 执行JS文件并获取返回值
ctx = execjs.compile(js_code)
result = ctx.call('some_function')

# 检测编码类型并解码返回数据
encoding = chardet.detect(result)['encoding']
decoded_result = result.decode(encoding)
print(decoded_result)

在上面的示例中,我们首先使用with open()语句加载JS文件,然后使用execjs库执行JS代码并获取返回值。接下来,我们使用chardet库检测返回值的编码类型,并将其解码为Python字符串。最后,我们打印解码后的结果。

需要注意的是,使用chardet库检测编码类型并不总是可靠的。如果可能的话,最好使用标准的字符编码,如UTF-8,以确保数据能够正确解码。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632