简体   繁体   English

nightmare.js-$未定义

[英]nightmare.js - $ not defined

I want to use jquery in my web scraping with nightmare.js . 我想在使用nightmare.js网络抓取中使用jquery Based on this tutorial , I can just inject the jquery and copy the file to the same root folder. 基于本教程 ,我可以inject jquery并将文件复制到相同的根文件夹。 But somehow I still get error: 但是我仍然会出错:

ReferenceError: $ is not defined ReferenceError:未定义$

Below is my code: 下面是我的代码:

var Nightmare = require('nightmare');

new Nightmare()
  .goto('http://google.com')
  .inject('js', 'jquery.min.js')
  .wait()
  .run(function(err, nightmare) {
    if (err) {
      console.log(err);
    };

    var items = [];

    $('.someclass').each(function(){//<-- error - $ not defined
        item = {};
        item.value = $(this).val();
        items.push(item);
    });
    console.log(items);
    });

To be able to interact with the page and its variables, you'll need to use .evaluate(fn) : 为了能够与页面及其变量进行交互,您需要使用.evaluate(fn)

Invokes fn on the page with arg1, arg2,... . 使用arg1, arg2,...调用页面上的fn

.evaluate() changes the context of the fn to that of the page, so that it can be execute as though it's client-side code, with access to the window , document , $ , and any other globals. .evaluate()fn的上下文更改为页面的上下文,以便可以像访问客户端代码一样执行它,并且可以访问windowdocument$和任何其他全局变量。

Also, since you've mentioned using version 2.10, the .run() function from 1.x versions has been replaced by Promise s , so you'll want to use .then() and .catch() to handle successes and errors, respectively. 此外,由于您已经使用2.10版所提到的, .run()从1.x版的功能已经换成Promise小号 ,所以你要使用的.then().catch()来处理成功和错误, 分别。

For your snippet: 对于您的摘要:

new Nightmare()
  .goto('http://google.com')
  .inject('js', 'jquery.min.js')
  .wait()
  .evaluate(function() {
    var items = [];

    $('.someclass').each(function(){
        item = {};
        item.value = $(this).val();
        items.push(item);
    });

    console.log(items);
  })
  .then(function () {
    console.log('Done');
  });
  .catch(function (err) {
    console.log('Error', err);
  });

The project's readme includes a few examples of this method chain . 该项目的自述文件包含此方法链的一些示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM