1. 什么是js2py
- 将JavaScript转换为Python代码。Js2Py能够翻译和执行几乎任何JavaScript代码。Js2Py是用纯python编写的,没有任何依赖关系。基本上是纯python中JavaScript核心的实现。
- 项目地址: js2py
- 模块安装:
pip install js2py
2. js2py初探
2.1 在python中执行js代码
import js2py
js2py.eval_js('console.log("hello world")')
func_js = """function add(a,b){return a+b}"""
add = js2py.eval_js(func_js)
print(add(1,3))
2.2 把js代码翻译成python代码
- .translate_js
- .translate_file
import js2py
print(js2py.translate_js("console.log('hello world')"))
js2py.translate_file('a.js','b.py')
2.3 在js代码中使用函数
import js2py
js_code = """
pyimport requests
console.log('导入成功');
var response = requests.get('http://www.baidu.com');
console.log(response.url);
console.log(response.content);
"""
js2py.eval_js(js_code)