python中运行js代码 js2py
安装
pip install js2py
js2py的简单用法
import js2py js = """ function add(a, b) { return a + b } """ add = js2py.eval_js(js) r = add(1, 2) + 3 print(r) >>>6
进阶用法
js = """ var a = 10; function f(x) { return x*x }; """ context = js2py.EvalJs() context.execute(js) print(context.a) # 获取值 10 print(context.f('9', 0,)) # 获取函数并执行 81 print(context.f.toString()) # 获取函数 function f(x) { [python code] } print(context.f.constructor) # 获取函数 'function Function() { [python code] }' # 定制属性 context.foo = [1,2,3] context.foo.push(4) print(context.foo.to_list()) # [1, 2, 3, 4]
运行结果
6 10 81 function f(x) { [python code] } 'function Function() { [python code] }' [1, 2, 3, 4]
数据类型转换标
Boolean -> bool String -> unicode Number -> float (or int/long if whole number) undefined -> None null -> None OTHER -> JsObjectWrapper
JsObjectWrapper支持:getitem,getattr,setitem,setattr,repr和
call。此外,如果要将其
转换为内置python类型,它具有to _list和to _dict方法 。
js = js2py.eval_js('d={a: 1, b: 2}') print(js) # {'a': 1, 'b': 2} print(type(js)) # <class 'js2py.base.JsObjectWrapper'> #该类型为字典的存储 print(js.a) # 1 # 取值方法 print(js['a']) # 1 # 取值方法 js.b = 20 # 修改属性方法 print(js) # {'a': 1, 'b': 20} js ['c'] = 30 # 设置属性方法 print(js) # {'a': 1, 'b': 20, 'c': 30} print(js.to_dict()) #{'a': 1, 'b': 20, 'c': 30} # 该方法转化为字典方法
print(js2py.translate_js('var $ = 5')) # from js2py.pyjs import * # # setting scope # var = Scope( JS_BUILTINS ) # set_global_object(var) # # # Code follows: # var.registers(['$']) # var.put('$', Js(5.0))
最后,Js2Py还支持从中导入任何Python代码的JavaScript
使用'pyimport'语句:
x = """ pyimport requests; var result = requests.get("https://www.baidu.com/"); console.log(result.text.length) """ print(js2py.eval_js(x))
调用示例
#!/usr/bin/env python3.6 # -*- coding:utf-8 -*- # @Author: Irving Shi import json import requests import js2py from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" } def get_company(key): res = requests.get("https://aiqicha.baidu.com/s?q=" + key, headers=headers) soup = BeautifulSoup(res.text, features="lxml") tag = soup.find_all("script")[2].decode_contents() context = js2py.EvalJs() context.execute(tag) res = context.window.pageData.result.resultList[0] return res.to_dict() res = get_company("91360000158304717T") for i in res.items(): print(i)