pip install PyExecJS
PyExecJS 的基本使用:
>>> importexecjs>>> 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
这里使用了一个网站的网页做示例,它的源代码中有这么一段
我们的目标是提取图中的json数据,代码如下:
Pythonimportrequestsimportreimportexecjsfrom lxml importetreefrom pprint importpprint
url= 'https://www.madewell.com/cn/madewell_category/SHIRTSTOPS/topsblouses/PRDOVR~F9375/F9375.jsp'res=requests.get(url)
doc=etree.HTML(res.text)
data= ''.join(doc.xpath('//script[contains(text(),"var data")]/text()'))
json_raw= re.search('({[\S\s]*\})',data).group(1)
jsn=execjs.eval(json_raw)
pprint(jsn)
执行结果如下图:
那么 怎么执行一个.js后缀的文件呢
importexecjs
with open("baidujs.js") as f:
jsData=f.read()#e是 baidujs.js 的一个js 函数
p = execjs.compile(jsData).call("e",inputData)
p 获取的就是函数执行的返回值