python3调用js的库之execjs

针对现在大部分的网站都是使用js加密,js加载的,并不能直接抓取出来,这时候就不得不适用一些三方类库来执行js语句


执行JS的类库:execjs,PyV8,selenium,node

这里主要讲一下execjs,一个比较好用且容易上手的类库(支持py2,与py3),支持 JS runtime。

官网:https://pypi.org/project/PyExecJS/

(一)安装:

pip install PyExecJS

or

easy_install PyExecJS

(二)运行时环境

execjs会自动使用当前电脑上的运行时环境(建议用nodejs,与Phantomjs)

>>> execjs.get().name # this value is depends on your environment.
>>> os.environ["EXECJS_RUNTIME"] = "Node"
>>> execjs.get().name
'Node.js (V8)'

通过运行时环境运行js

>>> default = execjs.get() # the automatically picked runtime
>>> default.eval("1 + 2")
3
>>> import execjs.runtime_names
>>> jscript = execjs.get(execjs.runtime_names.JScript)
>>> jscript.eval("1 + 2")
3
>>> import execjs.runtime_names
>>> node = execjs.get(execjs.runtime_names.Node)
>>> node.eval("1 + 2")
3

就好比是这样子的
image.png

(3)简单案例

>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> ctx = execjs.compile("""
...     function add(x, y) {
...         return x + y;
...     }
... """)
>>> ctx.call("add", 1, 2)
3

更多资源请访问:

https://blog.csdn.net/xudailong_blog/article/details/78762262

小密圈精品源码根据地

欢迎光临我的小网站:http://www.00reso.com

陆续优化中,后续会开发更多更好玩的有趣的小工具

猜你喜欢

转载自blog.csdn.net/xudailong_blog/article/details/81271302