【问题标题】:Scrape html from js with node.js and horseman使用 node.js 和 horseman 从 js 中抓取 html
【发布时间】:2015-10-12 15:53:11
【问题描述】:

我正在尝试使用此页面中的薪水信息抓取击球手数组: https://www.swishanalytics.com/optimus/mlb/dfs-batter-projections

我正在使用 node.js 和 node-horseman。

这是我的代码:

var Horseman = require('node-horseman');
var horseman = new Horseman();

horseman.open('https://www.swishanalytics.com/optimus/mlb/dfs-batter-projections');

if (horseman.status() === 200) {
    console.log('[+] Successful page opening')
    horseman.screenshot('image.png');
    console.log(horseman.html());
  }    
horseman.close();

问题是从 horseman.html() 的返回仍然有很多 JavaScript 并且不能用 Cheerio 之类的东西提取。如何以编程方式执行 javascript?

例如,如果我在同一链接中查看源代码,我会看到有击球手的区域以

开头
function Model(){ this.batterArray = 
[{"team_short":"rockies","mlbam_id":"571448","player_name":"Nolan Arenado",

显然这仍然是 javascript... 我假设在某些时候它必须被执行并转换为 HTML 以由浏览器呈现?

【问题讨论】:

  • 可以用cheerio完成,如果你有兴趣我可以教你怎么做。它会更容易使用,并返回文本或 json,但它不会像 PhantomJS 那样做截图。

标签: javascript node.js dom phantomjs


【解决方案1】:

我刚刚对此进行了测试,它似乎有效:

var Horseman = require('node-horseman');
var horseman = new Horseman();

horseman.open('https://www.swishanalytics.com/optimus/mlb/dfs-batter-projections');

if (horseman.status() === 200) {
    console.log('[+] Successful page opening')
    horseman.screenshot('image.png');
    var batters = horseman.evaluate(function(){
        return (new Model()).batterArray;
    });
    console.log(batters);
  }    
horseman.close();

这将为您提供一系列可在代码中使用的击球手。您可以将其写入文件或从中创建一个表。

【讨论】:

  • 搞定了...我在想盒子里的死点。
  • 当时这确实有效。 swishanalytics.com 的开发人员可能更改了可能破坏此示例的页面。
【解决方案2】:

它应该是这样工作的。

var Horseman = require('node-horseman');
var horseman = new Horseman();
horseman
 .open('https://www.swishanalytics.com/optimus/mlb/dfs-batter-projections')
 .status()
 .then((status) => {
   if(status === 200){
     console.log('[+] Successful page opening')
     horseman.screenshot('image.png');
     var batters = horseman.evaluate(function(){
       return (new Model()).batterArray;
     });
     console.log(batters);
   }else{
     console.log('no batters');
   }
 })
 .close();

【讨论】:

猜你喜欢
  • 2015-05-17
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
相关资源
最近更新 更多