How can I use persisted cookies from a file using phantomjs

后端 未结 2 1064
眼角桃花
眼角桃花 2020-12-01 01:42

I have some authentication requried to hit a particular url. In browser I need to login only once, as for other related urls which can use the session id from the cookie nee

2条回答
  •  星月不相逢
    2020-12-01 02:06

    The file created by the option --cookies-file=cookies.txt is serialized from CookieJar: there are extra characters and it's sometimes difficult to parse.

    It may looks like:

    [General]
    cookies="@Variant(\0\0\0\x7f\0\0\0\x16QList\0\0\0\0\x1\0\0\0\v\0\0\0{__cfduid=da7fda1ef6dd8b38450c6ad5632...
    

    I used in the past phantom.cookies. This array will be pre-populated by any existing Cookie data stored in the cookie file specified in the PhantomJS startup config/command-line options, if any. But you can also add dynamic cookie by using phantom.addCookie.

    A basic example is

    phantom.addCookie({
        'name':     'Valid-Cookie-Name',   /* required property */
        'value':    'Valid-Cookie-Value',  /* required property */
        'domain':   'localhost',           /* required property */
        'path':     '/foo',
        'httponly': true,
        'secure':   false,
        'expires':  (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
    });
    

    With these methods, it's not so difficult to implement your own cookie management logic.

提交回复
热议问题