PhantomJS网页超时

31

我已经设置了一个脚本来创建我们应用程序的网页截图。 一切都运行得很完美,直到我遇到一个带有损坏URL的图片:

 "<img src='http://testserver.our.intranet/fetch/image/373e8fd2339696e2feeb680b765d626e' />"

我已经成功使用以下方法在6秒后使脚本崩溃。在此之前,它只是一直循环。

但是,是否有可能忽略网络请求(即将图像从DOM中取出),然后继续创建缩略图,而不使用该图像(或者使用一个注入的遗失图像!)

var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

if (system.args.length < 3 || system.args.length > 5) {
    phantom.exit(1);
} else {
    address = system.args[1];
    output  = system.args[2];
    page.viewportSize = { width: 640, height: 640 };
    page.zoomFactor = 0.75;
    page.clipRect = { top: 10, left: 0, width: 640, height: 490 };
    try{
        page.open(address, function (status) {
            if (status !== 'success') {
                console.log('Unable to load the address!');
                phantom.exit();
            } else {
                window.setTimeout(function () {
                    page.render(output);
                    phantom.exit();
                }, 200);
            }
        });    
    } finally{
        setTimeout(function() {
            console.log("Max execution time " + Math.round(6000) + " seconds exceeded");
            phantom.exit(1);
        }, 6000);
    }
}

这是一个非常好的问题。我们有一个类似的问题,只不过它更难解决。我们有一个客户网站,其中包含编写不良的自定义JavaScript。它似乎导致Webkit挂起。我们有大量的网站需要测试,但如果客户的自定义js破坏了Webkit,则无法正常工作。计时器对象是一个很好的解决方案,但我想知道是否有其他解决方案。...? - cliffbarnes
1个回答

62

PhantomJS 1.9引入了一个新的设置,resourceTimeout,用于控制请求在被取消之前可以等待多长时间。除此之外,还有一个onResourceTimeout事件,会在请求超时时触发。

以下是一个代码片段,演示了上述所有内容:

var page = require('webpage').create();  
page.settings.resourceTimeout = 5000; // 5 seconds
page.onResourceTimeout = function(e) {
  console.log(e.errorCode);   // it'll probably be 408 
  console.log(e.errorString); // it'll probably be 'Network timeout on resource'
  console.log(e.url);         // the url whose request timed out
  phantom.exit(1);
};

page.open('http://...', function (status) {
...
}

很不幸,这些选项现在文档记录得很少。为了找到它们,我不得不阅读GitHub讨论PhantomJS源代码


2
资源超时(resourceTimeout)是否应该终止调用的PhantomJS进程?因为对我来说,它并没有。PhantomJS进程只是无限期地挂起。 - Donato
@Donato 我认为resourceTimeout只会触发某些事件,这些事件可以在 page.onResourceTimeout 中进行处理。 - Scadge
1
至少在版本1.9.8中,resourceTimeout会中断进程 - 因此PDF文件会损坏,但进程不会挂起。我还通过使用page.onResourceTimeout = function(request)来记录导致问题的资源。 - ESP32
不支持使用 page.onResourceTimeout = ...;,请改用 page.property('onResourceTimeout', ...)。有关更多 page#property 示例,请参阅 README 文件。 - user1709076

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接