学习爬虫第七天 js2py模块
1. js2py介绍
介绍: js2py是纯python实现的库,⽤于在python中运⾏js代码,本质上是将js代码翻译成python代码
作用: 用来处理一些js加密的数据,模拟发送js数据
常用的两个库: js2py, pyexecjs
2. js2py的安装
pip install js2py
3. js2py的简单使用
import js2py
js2py.eval_js('console.log("hello world")')
fun_js = """
function add(a,b){
return a+b
}
"""
add = js2py.eval_js(func_js)
print(add(1,2))
4. js2py代码翻译
参考示例:
import js2py
print(js2py.reanslate_js("console.log('hello world')"))
# 将js文件翻译成Python脚本
js2py.translate_file('test.js', 'test.py') # 第一个参数为需翻译的js文件,第二个为翻译后的文件
5. js2py代码中使用python函数
参考示例:
import js2py
# py中:
print("sum:", sum([1, 2, 3]))
# js2中
context = js2py.Evaljs({'python_sum': sum}) # 相当于定义了一个函数
print("context.python_sum:", context.python_sum)
js_code = """
python_sum([1,2,3])
""" # 传参
print("js_code运行结果:", context.eval(js_code))
6. js代码中导入Python模块并使用
示例参考:
import js2py
# 在js代码中导入Python模块并使用
# 使用pyimport语法
js_code = """
pyimport requests
console.log('导入成功');
var response = requests.get('http://www.baidu.com');
console.log(response.url);
console.log(response.content);
"""
js2py.eval_js(js_code)
7. 谷歌如何调试js
- 右键 检查工具
- 找到Consle点击