我试图从当用户向下滚动到底部(无限滚动)时动态生成内容的页面中抓取链接。我尝试过使用 Phantomjs 做不同的事情,但无法收集首页之外的链接。假设加载内容的底部元素有类.has-more-items
。它一直可用,直到滚动时加载最终内容,然后在 DOM 中变得不可用(display:none)。这是我尝试过的事情-
- 之后立即将 viewportSize 设置为较大的高度
var page = require('webpage').create();
page.viewportSize = { 宽度:1600,高度:10000,
};
- Using
page.scrollPosition = { top: 10000, left: 0 }
inside page.open
但没有效果,如-
page.open('http://example.com/?q=houston', function(status) {
if (status == "success") {
page.scrollPosition = { top: 10000, left: 0 };
}
});
- 也尝试把它放进去
page.evaluate
函数但这给出了
参考错误:找不到变量页面
- 尝试在里面使用 jQuery 和 JS 代码
page.evaluate
and page.open
但无济于事——
$("html, body").animate({scrollTop: $(document).height() }, 10,
功能() {
//console.log('检查执行情况');
});
照原样,也在里面document.ready
。同样对于 JS 代码 -
window.scrollBy(0,10000)
照原样,也在里面window.onload
我真的被它困扰了两天,但找不到方法。任何帮助或提示将不胜感激。
Update
我在以下位置找到了一段有用的代码https://groups.google.com/forum/?fromgroups=#!topic/phantomjs/8LrWRW8ZrA0
var hitRockBottom = false; while (!hitRockBottom) {
// Scroll the page (not sure if this is the best way to do so...)
page.scrollPosition = { top: page.scrollPosition + 1000, left: 0 };
// Check if we've hit the bottom
hitRockBottom = page.evaluate(function() {
return document.querySelector(".has-more-items") === null;
}); }
Where .has-more-items
是我想要访问的元素类,它最初在页面底部可用,当我们向下滚动时,它会进一步向下移动,直到加载所有数据然后变得不可用。
然而,当我测试时,很明显它正在进入无限循环而无需向下滚动(我渲染图片进行检查)。我尝试过更换page.scrollPosition = { top: page.scrollPosition + 1000, left: 0 };
也包含下面的代码(一次一个)
window.document.body.scrollTop = '1000';
location.href = ".has-more-items";
page.scrollPosition = { top: page.scrollPosition + 1000, left: 0 };
document.location.href=".has-more-items";
但似乎没有任何作用。