PhantomJS-默认使用LocalStorage打开页面

PhantomJS- open page with LocalStorage by default

本文关键字:LocalStorage 默认 PhantomJS-      更新时间:2023-09-26

我正在使用PhantomJS在JavaScript DOM操作发生后获取网页的生成源代码。这个网页只有一个<body>,没有别的。

重要提示 :此网页使用浏览器localStorage来生成网页。

我想在打开页面之前更改 PhantomJS 中的本地存储。

应用.js

var page = require('webpage').create();
page.open("https://sample.com")
setTimeout(function(){
    // Where you want to save it    
    page.render("screenshoot.png")  
    // You can access its content using jQuery
    var fbcomments = page.evaluate(function(){
        return $("body").contents().find(".content") 
    }) 
    phantom.exit();
}, 1000)
特定

域的 localStorage 仅在您打开该域上的页面时可用。您可以

  1. 在您感兴趣的域上打开一些 URL,
  2. 根据您的需要更改localStorage
  3. 在同一域上打开目标网址。

这可能看起来像这样:

page.open("https://sample.com/asdfasdf", function(){
    page.evaluate(function(){
        localStorage.setItem("something", "whatever");
    });
    page.open("https://sample.com", function(){
        setTimeout(function(){
            // Where you want to save it    
            page.render("screenshoot.png")  
            // You can access its content using jQuery
            var fbcomments = page.evaluate(function(){
                return $("body").contents().find(".content") 
            }) 
            phantom.exit();
        },1000)
    });    
});

也可以在步骤 1 中不打开整页。您也可以使用带有某些URL的虚拟页面。

page.setContent("", "https://sample.com"); // doesn't actually open any page
page.evaluate(function(){
    localStorage.setItem("something", "whatever");
});
page.open("https://sample.com", function(){
    setTimeout(function(){
        // Where you want to save it    
        page.render("screenshoot.png")  
        // You can access its content using jQuery
        var fbcomments = page.evaluate(function(){
            return $("body").contents().find(".content") 
        }) 
        phantom.exit();
    }, 1000)
});    

我用朋友的帮助解决了我的问题。我的解决方案是:

注意:我为完成加载页面设置了超时 10000(10 秒)。

var page = require('webpage').create();
page.open("https://sample.com", function(){
    page.evaluate(function(){
        var i = 0,
        oJson = jsonData,
        sKey;
        localStorage.clear();
        for (; sKey = Object.keys(oJson)[i]; i++) {
            localStorage.setItem(sKey,oJson[sKey])
        }
    });
    page.open("https://sample.com", function(){
        setTimeout(function(){
         page.render("screenshoot.png") 
            // Where you want to save it    
           console.log(page.content); //page source
            // You can access its content using jQuery
            var fbcomments = page.evaluate(function(){
                return $("body").contents().find(".content") 
            }) 
            phantom.exit();
        },10000)
    });    
});