# python使用execjs执行含有document、window等对象的js代码，使用jsdom解决

[En]

When we analyze the crawler, we sometimes encounter some encryption parameters, so we need to reverse analyze the js.

python执行js有一些第三方库

[En]

Because I use Python3, so I didn’t use PyV8 (the method of installing on the Internet, and I didn’t install it well, maybe I’m too stupid! If there is any trouble, please give me some advice)

[En]

I use js2py and execjs more often.

[En]

Once when I was analyzing js, I had found the corresponding encryption method. When I ran it on the browser, I got the result directly, a happy one.

[En]

Then I copied the js code, ran it through js2py in Python, found an error and said

ReferenceError: window is not defined


[En]

I feel desperate when I think of the objects in this browser, and then I wonder if execjs can break through this because it relies on node to execute.

[En]

The result still doesn’t work, because you can only run js syntax in node, and there are no objects such as window and document.

[En]

Later, by chance, we found that there is a library jsdom in node, which can generate the corresponding environment.

https://www.npmjs.com/package/jsdom

[En]

Global installation command

npm i jsdom -g


[En]

You can see that after the import, there are all kinds of environments, perfect.

[En]

So we just need to add the following code to the front of the corresponding js code to work properly.

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(<!DOCTYPE html><p>Hello world</p>);
window = dom.window;
document = window.document;
XMLHttpRequest = window.XMLHttpRequest;



[En]

After installing jsdom globally, there is no problem with writing it as above in node, but if we want to use it in python, we cannot install it globally.

[En]

If you install globally, the following error will be reported when using it, saying that jsdom could not be found

execjs._exceptions.ProgramError: Error: Cannot find module 'jsdom'


[En]

There are two solutions.

1.就是在python执行文件所在的运行目录下，使用npm安装jsdom
2. 使用cwd参数，指定模块的所在目录，比如，我们在全局安装的jsdom，在cmd里通过npm root -g 可以查看全局模块安装路径: C:\Users\w001\AppData\Roaming\npm\node_modules

[En]

When we use it, the code can be written as follows

import execjs
with open(r'&#x8981;&#x8FD0;&#x884C;&#x7684;.js','r',encoding='utf-8') as f:
ct = execjs.compile(js,cwd=r'C:\Users\w001\AppData\Roaming\npm\node_modules')


Original: https://www.cnblogs.com/huchong/p/11044238.html
Author: 听风。
Title: python使用execjs执行含有document、window等对象的js代码，使用jsdom解决

(0)