python调用js代码---PyV8

2017-12-11  本文已影响0人  玩阿轲睡妲己

背景:爬某网站数据。需要携带参数发POST请求,参数在网页js中,js太复杂,不便用python模拟。所以直接用python执行js函数,得到参数。

PyV8执行js获取参数.png
import PyV8
ctxt = PyV8.JSContext()
ctxt.enter()
ctxt.eval(""" function createGuid() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
createGuid() + createGuid() + "-" + createGuid() + "-" + createGuid() + createGuid() + "-" + createGuid() + createGuid() + createGuid(); """)
>>> with PyV8.JSContext() as ctxt:
...     ctxt.enter()
...     print ctxt.eval(""" function createGuid() {return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);}createGuid() + createGuid() + "-" + createGuid() + "-" + createGuid() + createGuid() + "-" + createGuid() + createGuid() + createGuid(); """)
...
58076022-485c-70707e9f-2e4e2d2e055e

Python 和 Js 之间的变量交互

import PyV8
with PyV8.JSContext() as env1:
    env1.eval("""
                var_i = 1;
                var_f = 1.0;
                var_s = "test";
                var_b = true;
            """)
    vars = env1.locals
    var_i = vars.var_i
    print var_i
import PyV8
with PyV8.JSContext() as env1:
    env1.securityToken = "foo"
    env1.locals.prop = 3
    print int(env1.eval("prop"))
上一篇 下一篇

猜你喜欢

热点阅读