【发布时间】:2018-10-06 21:14:13
【问题描述】:
我正在使用phantom 6.0.3 来抓取网页。这是初始设置:
(async function () {
const instance = await phantom.create(['--ignore-ssl-errors=yes', '--load-images=no', '--web-security=false'], {logLevel: 'error'});
const page = await instance.createPage();
await page.on('onResourceRequested', function (requestData) {
console.info('Requesting', requestData.url);
});
const url = // Some url
const status = await page.open(url);
const content = await page.evaluate(function () {
return document.querySelector('ul > li');
});
const contentLength = content.length // 5
//Code Block 2 goes here
})();
到目前为止一切正常。它能够成功确定content 的长度为5(有5 个li 项)。所以我现在要做的是获取每个li 元素的innerText...这就是我遇到问题的地方。
我尝试使用for loop 来检索每个li 元素的innerText,但它总是返回null。这是我尝试过的:
//Code Block 2:
for (let i = 0; i < contentLength; i++) {
const info = await page.evaluate(function () {
const element = document.querySelector('ul > li');
return element[i].innerText;
});
console.log(info); // this returns null 5 times
}
我不知道发生了什么。我可以给出一个特定的索引来返回,例如:return element[3].innerText,这会给我正确的innerText,但我无法通过loop 得到这个工作
【问题讨论】:
-
如果
return element[3].innerText有效,那么您可以使用page.evaluate的inside 循环,而不是外部循环吗? -
不幸的是,
phantom中的循环之类的东西在page.evaluate中不起作用。根据phantom文档:The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
标签: javascript node.js web-scraping phantomjs