40、反爬之JS逆向
Python 调用 JS 的几种方式
日常 Web 端爬虫过程中,经常会遇到参数被加密的场景,因此,我们需要分析网页源代码
通过调式,一层层剥离出关键的 JS 代码,使用 Python 去执行这段代码,得出参数加密前后的 Python 实现
//计算两个数的和
function add(num1, num2) {
return num1 + num2;
}
1. PyExecJS
https://github.com/doloopwhile/PyExecJS
PyExecJS 是使用最多的一种方式,底层实现方式是:在本地 JS 环境下运行 JS 代码
pip install PyExecJS
调用JS代码
import execjs
js_content = '''
function add(num1, num2) {
return num1 + num2;
}
'''
# 编译加载js字符串
pej = execjs.compile(js)
rs = pej.call("add", 2, 3)
print(rs)
2. js2py
https://github.com/PiotrDabkowski/Js2Py
js2py作为一个纯 Python 实现的 JS 解释器,可以完全脱离 JS 环境,直接将 JS 代码转换为 Python 代码
pip install js2py
然后使用 js2py 中的EvalJs()方法生成一个上下文对象
import js2py
js_content = '''
function add(num1, num2) {
return num1 + num2;
}
'''
context = js2py.EvalJs()
context.execute(js_content)
result = context.add(1, 2)
print(result)
3. node
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。Node.js 的包管理器 npm,是全球最大的开源库生态系统
3.1 安装
3.2 使用Node执行JS
function add1(a, b) {
return a + b
}
//外部传参设置:与方法一相同
var a = parseInt(process.argv[2]);
var b = parseInt(process.argv[3]);
console.log(add1(a,b));
3.2.1 方法1
import os
a=1
b=2
command2 = 'node ./test_nodejs.js 1 2'
with os.popen(command2) as nodejs2:
result2= nodejs2.read().replace('\n', '')
print(result2)
3.2.2 方法2
import subprocess
a=1
b=2
p = subprocess.Popen('node ./test_nodejs.js 1 2'.split(), stdout=subprocess.PIPE)
out = p.stdout.read()
print('out:',out.decode())