1. 程式人生 > 實用技巧 >python呼叫js的方法

python呼叫js的方法

python呼叫js的方法

安裝

pip install js2py

js2py的簡單用法

import js2py

js = """
function add(a, b) {
    return a + b
}
"""
add = js2py.eval_js(js)
r = add(1, 2) + 3
print(r)

>>>6

進階用法

js = """
var a = 10; 
function f(x) {
    return x*x
};
"""
context = js2py.EvalJs()
context.execute(js)

print(context.a)    #
獲取值 10 print(context.f('9', 0,)) # 獲取函式並執行 81 print(context.f.toString()) # 獲取函式 function f(x) { [python code] } print(context.f.constructor) # 獲取函式 'function Function() { [python code] }' # 定製屬性 context.foo = [1,2,3] context.foo.push(4) print(context.foo.to_list()) # [1, 2, 3, 4]

執行結果

6
10
81
function f(x) { [python code] }
'function Function() { [python code] }'
[1, 2, 3, 4]

資料型別轉換標

Boolean -> bool
String -> unicode
Number -> float (or int/long if whole number)
undefined -> None
null -> None
OTHER -> JsObjectWrapper

JsObjectWrapper支援:getitem,getattr,setitem,setattr,repr和
call。此外,如果要將其
轉換為內建python型別,它具有to \ _list和to \ _dict方法。

js = js2py.eval_js('d={a: 1, b: 2}')
print(js)   # {'a': 1, 'b': 2}

print(type(js)) # <class 'js2py.base.JsObjectWrapper'>  #該型別為字典的儲存

print(js.a) # 1 # 取值方法

print(js['a']) # 1  # 取值方法

js.b = 20   # 修改屬性方法
print(js)   # {'a': 1, 'b': 20}
js ['c'] = 30   # 設定屬性方法
print(js)   # {'a': 1, 'b': 20, 'c': 30}
print(js.to_dict()) #{'a': 1, 'b': 20, 'c': 30} # 該方法轉化為字典方法

print(js2py.translate_js('var $ = 5'))
# from js2py.pyjs import *
# # setting scope
# var = Scope( JS_BUILTINS )
# set_global_object(var)
#
# # Code follows:
# var.registers(['$'])
# var.put('$', Js(5.0))

最後,Js2Py還支援從中匯入任何Python程式碼的JavaScript
使用'pyimport'語句:

x = """
pyimport requests;
var result = requests.get("https://www.baidu.com/");

console.log(result.text.length)
"""
print(js2py.eval_js(x))

呼叫示例

#!/usr/bin/env python3.6
# -*- coding:utf-8 -*-
# @Author: Irving Shi


import json
import requests
import js2py

from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}


def get_company(key):
    res = requests.get("https://aiqicha.baidu.com/s?q=" + key, headers=headers)
    soup = BeautifulSoup(res.text, features="lxml")
    tag = soup.find_all("script")[2].decode_contents()
    context = js2py.EvalJs()
    context.execute(tag)
    res = context.window.pageData.result.resultList[0]
    return res.to_dict()


res = get_company("91360000158304717T")
for i in res.items():
    print(i)