我想用PhantomJS,特别是与其示例捆绑在一起的waitFor脚本。我的测试目的是检查网站lipsum.com的英文版和法文版是否可用。这是我的剧本:
var page = require('webpage').create(),
server = 'http://www.lipsum.com',
languages = ['en', 'fr'];
page.open(server, 'get', '', function (status) {
if (status !== 'success') {
console.log('Unable to reach the URL!');
} else {
check(languages.shift());
}
});
function check(currentLanguage) {
console.log('Checking '+currentLanguage);
waitFor(function() {
var classes = page.evaluate(function() {
// Checks if the current language is selected
return document.getElementsByClassName('zz')[0].className;
});
console.log("Classes for the selected element : " + classes);
return classes.indexOf(currentLanguage) === 0;
}, function() {
console.log(currentLanguage+' has been looked up.');
currentLanguage = languages.shift();
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function (language) {
// We click on the link related to the next language of the stack
$('.'+language).trigger('click');
}, currentLanguage);
});
check(currentLanguage);
});
}
我想要的是显示英文,然后是法文版本的页面。相反,我得到以下日志:
Checking en
Classes for the selected element : en zz
'waitFor()' finished in 500ms.
en has been looked up.
Checking fr
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
Classes for the selected element : en zz
'waitFor()' timeout
看起来没有触发链接上的点击,但我无法理解原因。
答案 0 :(得分:0)
问题似乎是$.click
无效。您应该使用this question中的解决方案。
另一件事是你分裂你的控制流程。 page.includeJs
和check
是异步函数。它们必须是嵌套的,不应该一个接一个地来,因为如果你这样做,你只会邀请混乱。由于你不再需要jQuery,这只是对未来的建议。
你必须记住的另一件事是超时。页面相对较慢,因此3秒的超时有点慢。您应该将waitFor
的超时时间增加到10秒甚至更好,为下一页加载时注册事件处理程序。在下面的代码中,我做了两个。我还添加了适当的暂停标准。
waitFor(function() {
var classes = page.evaluate(function() {
// Checks if the current language is selected
return document.getElementsByClassName('zz')[0].className;
});
console.log("Classes for the selected element : " + classes);
return classes.indexOf(currentLanguage) === 0;
}, function() {
console.log(currentLanguage+' has been looked up.');
if (languages.length === 0) {
console.log("Done");
phantom.exit();
}
currentLanguage = languages.shift();
//page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.onLoadFinished = function(){
check(currentLanguage);
};
page.evaluate(function (language) {
// We click on the link related to the next language of the stack
var ev = document.createEvent("MouseEvent");
ev.initMouseEvent(
"click", true, true, window, null,
0, 0, 0, 0, false, false, false, false, 0, null
);
document.querySelector('.'+language).dispatchEvent(ev);
}, currentLanguage);
//});
}, 10000);