Python执行js字符串
Jeff的技术栈 人气:1方法
执行大型js时有点慢
特殊编码的输入或输出参数会出现报错,解决方法:
可以把输入或输出的参数用base64编码一下。base64都是英文和数字,没有特殊字符了
1--js2py
pip insatll js2py # 获取执行JS的环境 context = js2py.EvalJs() # 加载执行 context.execute('放JS字符代码')
2--execjs
import execjs print(execjs.get().name) # Node.js (V8)
import execjs user_id = '3232597584' url = f'https://www.toutiao.com/toutiao/api/pc/feed/?min_behot_time=1588149898&category=__all__&utm_source=toutiao&widen=1&tadrequire=true&user_id={user_id}&visited_uid={user_id}' js_index = """ js """ # 打开js文件读取 # new_url = execjs.compile(open("/Users/ts/Desktop/Jeff/今日头条/new_sign.js").read()).call('get_sigtrue', url) # 读取js字符串 new_url = execjs.compile(js_index).call('get_sigtrue', url) print(new_url)
3--execjs
import execjs def get_js(): f = open("./new_sign.js", 'r', encoding = 'UTF-8') line = f.readline() htmlstr = '' while line: htmlstr = htmlstr + line line = f.readline() return htmlstr jsstr = get_js() ctx = execjs.compile(jsstr) user_id = '3232597584' url = f'https://www.toutiao.com/toutiao/api/pc/feed/?min_behot_time=1588149898&category=__all__&utm_source=toutiao&widen=1&tadrequire=true&user_id={user_id}&visited_uid={user_id}' print(ctx.call('getUrl', url))
加载全部内容