Python中执行JS代码,通常两个库:js2py,pyexecjs

1、安装

  1. pip install js2py

2、直接执行js代码

js2py.eval_js(str),str是js代码的Python字符串,eval_js方法将js代码直接在Python中执行

  1. import js2py
  2. js_func = """
  3. function add(a, b){
  4. return a+b
  5. }
  6. """
  7. add = js2py.eval_js(js_func)
  8. print(add(1, 2))
  9. js2py.eval_js('console.log("hello wrold")')

3、翻译js代码

  1. import js2py
  2. # 将js代码翻译成Python脚本
  3. print(js2py.translate_js("console.log('hello world')"))
  4. # 将js文件翻译为Python脚本
  5. js2py.translate_file('test.js', 'test.py')

4、在js代码中使用python函数

  1. import js2py
  2. print("sum: ", sum([1, 2, 3]))
  3. context = js2py.EvalJs({'python_sum': sum})
  4. print("context.python_sum: ", context.python_sum)
  5. js_code = """
  6. python_sum([1,2,3])
  7. """
  8. print("js_code运行结果: ", context.eval(js_code))

5、js代码中导入Python模块并使用

  1. import js2py
  2. # 在js代码中导入Python模块并使用
  3. # 使用pyimport语法
  4. js_code = """
  5. pyimport requests
  6. console.log('导入成功');
  7. var response = requests.get('http://www.baidu.com');
  8. console.log(response.url);
  9. console.log(response.content);
  10. """
  11. js2py.eval_js(js_code)

6、执行js代码中的某个函数

  1. import js2py
  2. js_code = """
  3. let n = 10;
  4. function test(){
  5. if(n == 10){
  6. console.log(n);
  7. }
  8. }
  9. """
  10. js_obj = js2py.EvalJs() #实例化解析js对象
  11. js.execute(js_code) #js转python代码
  12. js.test() #调用js中的TL函数