【问题标题】:phantom - can't use loop with page.evaluate幻影 - 不能在 page.evaluate 中使用循环
【发布时间】: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.evaluateinside 循环,而不是外部循环吗?
  • 不幸的是,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


【解决方案1】:

PhantomJS 在不同的上下文中评估函数,因此它不知道参数i

您应该将i 传递给评估函数,以便将其转发给浏览器进程:

for (let i = 0; i < contentLength; i++) {
    const info = await page.evaluate(function (index) { // notice index argument
        const element = document.querySelector('ul > li');
        return element[index].innerText;
    }, i); // notice second argument is i

    console.log(info);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多