简体   繁体   English

未找到特定请求时如何退出PhantomJS?

[英]How can I exit PhantomJS when a specific request is not found?

The problem is, some sites contain the request to test.com/test.aspx and some don't. 问题是,有些网站包含对test.com/test.aspx的请求,而有些则没有。

If the request exists, it should print the JSON and exit. 如果请求存在,则应打印JSON并退出。 If the request does not exist, it should exit too - at the moment, it stays open in this case. 如果请求不存在,它也应该退出-目前,在这种情况下,它保持打开状态。

Also, how could I make the code better? 另外,如何使代码更好? Maybe even faster if that's possible? 如果可能的话甚至更快?

My JS code: 我的JS代码:

var Url = "http://www.test.de";
var params = new Array();
var webPage = require('webpage');
var page = webPage.create();
var targetJSON = {};
page.open(Url);
page.onResourceRequested = function(requestData, networkRequest) {
var match = requestData.url.match(/test.com\/test.aspx/g);
if (match != null) {
    var targetString = decodeURI(JSON.stringify(requestData.url));
    var klammerauf = targetString.indexOf("{");
    var jsonobjekt = targetString.substr(klammerauf,     (targetString.indexOf("}") - klammerauf) + 1);
    targetJSON = (decodeURIComponent(jsonobjekt));
    console.log(targetJSON);
    phantom.exit();
} 

};

I tried to add 我试图添加

} else {
  phantom.exit();
}

and

} if (match == null) {
phantom.exit();
}

but nothing solves my problem. 但是没有什么能解决我的问题。

If you want to check whether something doesn't exist, then you need to check all things to see if they are not it or as first-order logic : 如果要检查是否不存在某物,则需要检查所有事物以查看它们是否不存在或作为一阶逻辑 ∃xP(x)∀x¬P(x) .

You first need to see all requests to see whether your intended request was there. 首先,您需要查看所有请求,以查看是否有预期的请求。 For example like this: 例如这样:

var found = false;
page.onResourceRequested = function(requestData, networkRequest) {
    var match = requestData.url.match(/test.com\/test.aspx/g);
    if (match != null) {
        var targetString = decodeURI(JSON.stringify(requestData.url));
        var klammerauf = targetString.indexOf("{");
        var jsonobjekt = targetString.substr(klammerauf,     (targetString.indexOf("}") - klammerauf) + 1);
        targetJSON = (decodeURIComponent(jsonobjekt));
        console.log(targetJSON);
        found = true;
        phantom.exit();
    } 
};
page.open(Url, function(){
    setTimeout(function(){
        console.log("found: " + found); // will always print "false"
        phantom.exit();
    }, 1000);
});

I solved this with a global variable which denotes whether the request was found. 我用一个全局变量解决了这个问题,该变量表示是否找到了请求。 If it wasn't, then you can exit PhantomJS. 如果不是,则可以退出PhantomJS。 If wait until the page is loaded and an additional waiting time in case there are Ajax requests. 如果等待直到页面被加载,并且有更多的等待时间(如果有Ajax请求)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM