我正在尝试从具有多个页面的网站中获取多个元素。我目前正在使用 PhantomJS 来完成这项工作,我的代码几乎可以正常工作,但问题是我的代码在第一页上抓取了两次,即使(根据日志)我似乎已经移到了第二页。
代码如下:
var page = require('webpage').create();
page.viewportSize = { width: 1061, height: 1000 }; //To specify the window size
page.open("website", function () {
function fetch_names(){
var name = page.evaluate(function () {
return [].map.call(document.querySelectorAll('div.pepitesteasermain h2 a'), function(name){
return name.getAttribute('href');
});
});
console.log(name.join('\n'));
page.render('1.png');
window.setTimeout(function (){
goto_next_page();
}, 5000);
}
function goto_next_page(){
page.evaluate(function () {
var a = document.querySelector('#block-system-main .next a');
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
waitforload = true;
});
fetch_names();
}
fetch_names();
});
您可以自己尝试以了解所有这些是如何工作的。
最佳答案
通过将 setTimeout()
从 fetch_names
移动到 goto_next_page
,您需要在点击之后等待页面加载,而不是在点击之前:
function fetch_names(){
var name = page.evaluate(function () {
return [].map.call(document.querySelectorAll('div.pepitesteasermain h2 a'), function(name){
return name.getAttribute('href');
});
});
console.log(name.join('\n'));
page.render('1.png');
goto_next_page();
}
function goto_next_page(){
page.evaluate(function () {
var a = document.querySelector('#block-system-main .next a');
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
waitforload = true;
});
window.setTimeout(function (){
fetch_names();
}, 5000);
}
请注意,除了静态超时之外,还有更多方法可以等待。相反,您可以
注册到
page.onLoadFinished
event :page.onLoadFinished = fetch_names;
使用 examples 中的
waitFor()
函数等待特定选择器出现.
关于javascript - 如何在 PhantomJS 中转到下一页进行抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32979753/