How to use Phantomjs' cookie API?
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
tmaster
Linux & FLOSS advocate, Arsenal FC Fan. Software Engineer, Geek. like to have a laugh.
Updated on June 18, 2022Comments
-
tmaster almost 2 years
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.
-
tmaster over 11 yearsI don't have the user password, only the csrftoken and the sessionid. And I found out that using --cookies-file parameter does not load cookie from the file, it actually saves the cookie into the file. I tried to use the addCookie function, but does not work with the format like
{'csrftoken':'', 'sessionid':''}
. Any ideas? Thanks -
Justin Bicknell over 11 yearsI think you have the wrong syntax for addCookie - see github.com/ariya/phantomjs/wiki/…
-
Justin Bicknell over 11 yearsI've updated the answer to include the addcookie method.. good call
-
tmaster over 11 yearsI saw that function already, but it does not work when I do
phantom.addCookie({'domain':'localhost', 'csrftoken':'f3da886168fae33b840e7f6c93240dff'});
-
Justin Bicknell over 11 yearstry the following: phantom.addCookie({'domain':'localhost', 'name':'csrftoken', 'value':'f3da886168fae33b840e7f6c93240dff'});
-
tmaster over 11 yearsYe, it works, but it does not seem enough for phantom to log in. I think I will find a way for phantom to log in I guess. I will accept the answer, at least you helped me to figure out how to use the cookie API, but if you have any other ideas, I will really appreciate it.
-
Justin Bicknell over 11 yearshave you inspected the request in a proxy yet? There has to be a noticeable difference between the browsers request and phantoms request
-
tmaster over 11 yearsAddCookie solution works, my bad it didn't work, I passed in the wrong url. Thanks.