We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
最近在用 node 学写爬虫,也可以叫模拟登陆,遇到某个网站在返回的 HTML 中插入了一个生成页面token的script。
这个HTML的结构大概类似
<!Doctype html> <html> <head></head> <body> <div></div> <script> (function (w) { w.token = (function () { // .... // 生成token return token; })();; })(window); </script> </body> </html>
首先拿到这个页面,然后获取script标签的表达式字符串,剩下的事就是怎样执行表达式字符串,并获取token。
在此处的情景中用eval也是挺不错的选择,但是既然 JS 不推荐这种用法,那我们就换成 new Function 来做。
看下 new Function 的用法如下
new Function ([arg1[, arg2[, ...argN]],] functionBody)
new Function会返回一个函数。例如 fn = new Function('a', 'b', 'return a + b') 会返回一个函数对象
fn = new Function('a', 'b', 'return a + b')
fn = function(a, b) { return a + b }
so,我们可以使用 new Function 构造一个函数,用来执行获取到得表达式,并返回token。
fn = new Function('window', functionBody + ';return window.token') var token = fn({}) console.log(token)
构造的这个函数有个window形参,作为函数体中立即执行表达式的实参传入最内层的函数中。所以在最后执行的时候 return window.token 便会获得token 的内容。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
最近在用 node 学写爬虫,也可以叫模拟登陆,遇到某个网站在返回的 HTML 中插入了一个生成页面token的script。
这个HTML的结构大概类似
首先拿到这个页面,然后获取script标签的表达式字符串,剩下的事就是怎样执行表达式字符串,并获取token。
在此处的情景中用eval也是挺不错的选择,但是既然 JS 不推荐这种用法,那我们就换成 new Function 来做。
看下 new Function 的用法如下
new Function会返回一个函数。例如
fn = new Function('a', 'b', 'return a + b')
会返回一个函数对象so,我们可以使用 new Function 构造一个函数,用来执行获取到得表达式,并返回token。
构造的这个函数有个window形参,作为函数体中立即执行表达式的实参传入最内层的函数中。所以在最后执行的时候 return window.token 便会获得token 的内容。
The text was updated successfully, but these errors were encountered: