Python调用JS的四种方法
js代码:
function add(a,b){
return a+b;
}
1、PyExecJS
安装PyExecJS:
pip install PyExecJS
import execjs
def testJs():
with open("1.js",'r') as f:
js=execjs.compile(f.read())
res=js.call('add',2,3)
print(res)
testJs()
2、PyV8
【不推荐使用,年久失修】
安装PyV8:
pip install PyV8
import PyV8
ctxt = PyV8.JSContext()
ctxt.enter()
jsstr = '''
function add() {
let a = 1;
let b = 2;
return a+b;
}'''
result = ctxt.eval(jsstr)
print(result)
3、js2py
【Bug较多,性能不高,不建议使用】
安装js2py:
pip install js2py
import js2py
content = js2py.EvalJs() # 实例化解析js对象
with open("1.js",'r') as f:
content.execute(f.read()) # js转python代码
result = content.add(1,2)
print(result)
4、selenium
安装selenium:
pip install selenium
from selenium import webdriver
jsstr = '''
function add() {
var a = 1;
var b = 2;
return a+b;
}'''
# 调用js
driver = webdriver.Chrome()
result = driver.execute_script(jsstr)
print(result)

浙公网安备 33010602011771号