How to use Phantomjs' cookie API?

2019-03-11 10:30发布

问题:

I am trying to use rasterize.js from the phantomjs' exmaple folder to capture a web page into PDF. The problem I am having is that the web page requires user log in. Then I saw there is a cookie option for Phantomjs. The web site is Django powered just in case it matters.

So I logged into the site manfully, opened the firebug, and typed document.cookie in firebug. I got the cookie settings and put into my cookies.txt.

[http://localhost:7000]
csrftoken: f3da886168fae33b840e7f6c93240dff
sessionid: 27e90c3214b0ec94dadc739665724708
django_language: en

Then I used the rasterize.js to create the pdf like below:

phantomjs --cookies-file=cookies.txt examples/rasterize.js http://localhost:7000/reports /tmp/report.pdf

But the result is still the log in page.

回答1:

Have you tried automating the login process in PhantomJS, making sure to include cookies param? This way phantomjs can authenticate a user just like a browser would, using cookies.

Another option would be to inspect the requests using a proxy like fiddler, compare the request made from firefox that works and the request made from phantomjs that is not authenticated. The information in the header should tell you what you are missing.

You can add cookies by using the function phantomjs provides:

http://phantomjs.org/api/webpage/method/add-cookie.html