Python run-execute javascript

创建日期: 2022-06-15 12:25 | 作者: 风波 | 浏览次数: 13 | 分类: Python

使用 execjs

来源:https://www.cnblogs.com/xyou/p/16441902.html

因为先经过了编译,所以后面 call 函数的时候速度会快一些。

pip install pyexecjs -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com
yum install -y nodejs
import execjs  # 导入execjs处理库

print(execjs.get().name)  # 获取javascript的默认执行环境
# Node.js (V8)

# 需要先将即将执行的代码块编译一下
compile_code = execjs.compile(open('./hello_world.js', 'r', encoding='utf-8').read())

# 使用编译后的代码块call函数调用js文件中的hello_world函数
result = compile_code.call('hello_world','python')

print(result) # 输出结果 python

还可以使用eval函数进行调用

result = compile_code.eval("hello_world('python')")

print(result) # python

当然,也可以像js2py一样直接执行js代码块的。

result = execjs.eval('""+ new Date().getTime()')

print(result) # 1648986998002

方法一:使用 js2py

注意:使用 js2py.eval_js() 速度比较慢。

import js2py

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")

result = js2py.eval_js(js)  # executing JavaScript and converting the result to python string 

注:如果 js 返回的数据是个 json,还可以使用 result.to_dict() 把数据转换成 dict类型。

方法二:使用PyV8

注意⚠️:未进行验证。

import PyV8
ctx = PyV8.JSContext()
ctx.enter()

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
"""

print ctx.eval(js.replace("document.write", "return "))

方法三:使用 PyMiniRacer(一个v8的包装)

注意⚠️:未进行验证

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")
13 浏览
0 评论