簡體   English   中英

使用PhantomJS訪問HTML中的JS全局變量的值

[英]Accessing values of JS Global variables in HTML with PhantomJS

所以我有一段HTML看起來像這樣:

<html>
  <body>
    <script>
      var foo = {
        bar: []
      };
    </script>
  </body>
</html>

我正在嘗試使用PhantomJS提取foo.bar的值。 我該怎么做? 到目前為止,我知道我的結構如下:

var webPage = require('webpage'); 
var page = webPage.create();
page.open(MY_URL, function(status) {
  var foo = page.evaluate(function(){
    //gets javascript from the HTML in the response
    // and extracts foo from there
  });
});

console.log(someVar);
phantom.exit();

似乎您應該可以使用

var foo = page.evaluate(function() {
  return window.foo
})
console.log('foo =', foo)

這是您的做法,從幻影虛擬瀏覽器打開url,並從帶有幻影的網頁獲取javascript返回值

const phantom = require('phantom');


openUrl = (req, res, next) => {
    let url = 'your url goes here';
    const {content, returnedFromPage} = await loadJsSite(url);
    return res.json(returnedFromPage);
}

loadJsSite = async (url) => {
  return new Promise( async (resolve, reject) => {

    const instance = await phantom.create();
    const page = await instance.createPage();
    await page.on('onResourceRequested', function(requestData) {
      console.info('Requesting', requestData.url);
    });

    const status = await page.open(url);
    var returnedFromPage = await page.evaluate(function() {
            return document.title;
        });
    const content = await page.property('content');

    await instance.exit();

    return resolve({content: content, returnedFromPage: returnedFromPage});

  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM