我正在尝试使用PhantomJS即时加载一些Cookie,但出现一些错误。这是我的代码:
var page = require('webpage').create();
var cookieJson = require('cookie.json'); // local cookie file
phantom.cookiesEnabled = true; // Enable Cookies
phantom.clearCookies(); // Clear Old Cookies
for(var i = 0; i< cookieJson.length; i++) { //for each domain, try to add the cookie
var temp = cookieJson[i];
console.log(JSON.stringify(temp)); // This seems to print just fine
phantom.addCookie(temp); // this throws an exception
}
phantom.exit();
上面的代码引发以下异常:
incompatible type of argument(s) in call to addCookie(); candidates were
addCookie(QVariantMap)
我敢肯定,这里有一个简单的解决方案,但是我脑子僵了。我的印象是JSON.stringify
从JSON对象返回一个字符串。真正令人困惑的是,当我将其打印到控制台时,其外观与将其存储为时完全相同String
。我的数据如下所示:
{"domain": ".sweatytacobo.com",
"expires": "Tue, 10 Jun 2014 16:37:46 GMT",
"expiry": ,
"httponly": false,
"name": "__utmz",
"path": "/",
"secure": false,
"value": "268881515.13222266.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"}
当我将上面的内容用作字符串时,它可以毫无问题地添加。那为什么JSON.Stringify
给我麻烦呢?
编辑:
根据PhantomJS源代码的注释,将addCookie传递给QVariantMap,格式为:
{
* "name" : "cookie name (string)",
* "value" : "cookie value (string)",
* "domain" : "cookie domain (string)",
* "path" : "cookie path (string, optional)",
* "httponly" : "http only cookie (boolean, optional)",
* "secure" : "secure cookie (boolean, optional)",
* "expires" : "expiration date (string, GMT format, optional)"
* }
所以我不应该能够以某种方式传递JSON对象吗?
好吧,我知道了。PhantomJS addCookie对Cookie的格式非常挑剔。
基本上,为了转换JSON,您必须通过遍历JSON对象来提取值。例如:
var cookieJson = require('cookiefile.json');
// load in the cookies in JSON format from file
for(var i = 0; i< cookieJson.length; i++) {
var tempCookie = {};
tempCookie["name"] = cookieJson[i]["name"];
tempCookie["domain"] = cookieJson[i]["domain"];
tempCookie["value"] = cookieJson[i]["value"];
tempCookie["path"] = cookieJson[i]["path"];
tempCookie["session"] = cookieJson[i]["session"];
tempCookie["storeId"] = cookieJson[i]["storeId"];
// Here we are adding the relevant values as needed and in the proper format
var tempADD = {"domain": tempCookie["domain"],
"expires": tempCookie["expires"],
"expirationDate": 1402418266,
"httpOnly": tempCookie["httpOnly"],
"name": tempCookie["name"],
"path": tempCookie["path"],
"secure": tempCookie["secure"],
"value": tempCookie["value"],
"session": tempCookie["session"],
"storeId": tempCookie["storeId"]};
// Finally, we add the cookie. phantom.addCookie returns true if successful
if(phantom.addCookie(tempADD)){
console.log("Cookie Added!");
} else {
console.log("Cookie Failure: ");
console.log(JSON.stringify(tempADD)) // print the cookie which failed to load
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句