如何使用 node.js 抓取具有动态内容的页面?

2022-01-30 00:00:00 web-crawler node.js phantomjs javascript

我正在尝试抓取 网站,但我没有得到一些元素,因为这些元素是动态创建的.

I am trying to scrape a website but I don't get some of the elements, because these elements are dynamically created.

我在node.js中使用cheerio,我的代码如下.

I use the cheerio in node.js and My code is below.

var request = require('request');
var cheerio = require('cheerio');
var url = "http://www.bdtong.co.kr/index.php?c_category=C02";

request(url, function (err, res, html) {
    var $ = cheerio.load(html);
    $('.listMain > li').each(function () {
        console.log($(this).find('a').attr('href'));
    });
});

此代码返回空响应,因为当页面加载时,<ul id="store_list" class="listMain"> 为空.

This code returns empty response, because when the page is loaded, the <ul id="store_list" class="listMain"> is empty.

内容尚未附加.

如何使用 node.js 获取这些元素?如何抓取包含动态内容的页面?

How can I get these elements using node.js? How can I scrape pages with dynamic content?

推荐答案

给你;

var phantom = require('phantom');

phantom.create(function (ph) {
  ph.createPage(function (page) {
    var url = "http://www.bdtong.co.kr/index.php?c_category=C02";
    page.open(url, function() {
      page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
        page.evaluate(function() {
          $('.listMain > li').each(function () {
            console.log($(this).find('a').attr('href'));
          });
        }, function(){
          ph.exit()
        });
      });
    });
  });
});

相关文章