如何在node-js环境中使用phantomjs进行动态网页抓取

How to use phantomjs in node-js environment for dynamic-page web scraping?

本文关键字:phantomjs 动态 抓取 网页 node-js 环境      更新时间:2023-09-26

我正在进行web抓取,只需要完成一些任务。

我已经使用nodejs请求模块进行页面抓取。

它运行良好,非常适合cookie会话和所有内容。

但是,当需要渲染使用某些javascript框架构建的动态页面时,它会失败,如ANGULARBACKBONE等。

我正在努力让phantomjs克服这一点,因为我在谷歌上发现,克服这种情况是有帮助的。

我还为phantomjsphantom找到了一个nodejs桥

有了phantomjs和这个桥接模块,我就可以实现同样的事情了。

var phantom = require('phantom');
var fs = require('fs');
var sitepage = null;
var phInstance = null;
phantom.create()
    .then(instance => {
        phInstance = instance;
        console.log("Instance created");
        return instance.createPage();
    })
    .then(page => {
        sitepage = page;
        console.log("createing page");
        return page.open('https://paytm.com/shop/p/carrier-estrella-plus-1-5-ton-3-star-window-ac-LARCARRIER-ESTRPLAN5550519593A34?src=grid&tracker=%7C%7C%7C%7C%2Fg%2Felectronics%2Flarge-appliances%2F1-5-ton-3-star-ac-starting-at-rs-22699%7C88040%7C1');
    })
    .then(status => {
        //console.log(status);
        console.log("getting content of page");
        return sitepage.property('content');
    })
    .then(content => {
      console.log("success");
        //console.log(content);
        fs.writeFile("ok.text", content);
        sitepage.close();
        phInstance.exit();
    })
    .catch(error => {
      console.log("errr");
        //console.log(error);
        phInstance.exit();
    });

上面是我尝试加载的一个动态网站页面的代码,它是用angular框架构建的。

在上面的代码中,如果我遗漏了正确的东西,有人能指导我吗

在动态代码运行之前,您将获得页面的内容,需要等待加载完成。

page.open后面的块需要等待页面完成,如果你知道有一个元素正在从后端提取,你可以躺在那里等待该元素(例如,请参阅phantomjs-doc中的wait)。