Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

javascript - PhantomJS- open page with LocalStorage by default

I'm using PhantomJS to get the generated source of a web page after JavaScript DOM manipulations have taken place. This web page has JUST a <body> and nothing else.

Important: This web page uses browser's localStorage to generate the page.

I want to change LocalStorage in PhantomJS before opening the page.

App.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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

localStorage for a particular domain is only available when you open a page on that domain. You can

  1. open some URL on the domain you're interested in,
  2. change localStorage according to your needs,
  3. open your target URL on the same domain.

This can look like this:

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)
    });    
});

It's also possible not to open a full page in step 1. You can also use dummy page with some 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)
});    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...