如何在PhantomJS中获取JSessionID

时间:2014-11-11 03:34:21

标签: java javascript selenium-webdriver phantomjs

我不确定这个问题是否与PhantomJS或简单的Javascript有关。

我正在使用Ghostdriver打开网页并尝试捕获响应标头。 GhostDriver执行javascript并添加onResourceReceived事件。

像这样:

String responsescript = 
                "var page = this,"+
                "jsonResponse = \"\";"+
                "page.onResourceReceived = function (res) {"+
                "console.log(JSON.stringify(res));" /* This line works fine but i want to pass this data somehow to java program. To do that, i came up with the below alternative but it is failing*/
                "jsonResponse = jsonResponse + JSON.stringify(res, undefined, 4);"+
                "};"+
                "function getJsonResponse(){"+
                "return jsonResponse;"+
                "}";
ghostDriver.executePhantomJS(responsescript);
ghostDriver.get("cnn.com");
ghostDriver.executePhantomJS("getJsonResponse();");

以下消息始终失败:

{message=Can't find variable: getJsonResponse, line=1, stack=ReferenceError: Can't find variable: getJsonResponse

我只想在Java中的某些String变量中获取响应头,以便我可以在其中查找JSESSIONID ..

由于我的javascript技巧不佳,我无法解决这个简单的问题..

1 个答案:

答案 0 :(得分:0)

我不知道为什么我走了很长的路线,但经过ghostdriver(link)的例子之后..只有2行代码

太开心了......现在我可以安静地睡觉了。)

    String responsescript = 
                    "return JSON.stringify(this.cookies);";
    Object object = phantom.executePhantomJS(responsescript);

    System.out.println(((String)object));