简体   繁体   English

如何在phantomjs中使用jQuery

[英]How to use jQuery with phantomjs

I'm trying to do a simple test of jQuery with phantomjs: 我正在尝试使用phantomjs进行jQuery的简单测试:

var url = 'http://www.google.com/';
var page = require('webpage').create();
page.open(url, function () {
    page.injectJs('jquery.min.js');
    page.evaluate(function () {
        console.log($('title').text());
    });
    phantom.exit()
});

This should print out the title, but instead nothing happens. 这应该打印出标题,但是什么也没有发生。 Can somebody tell me what's wrong? 有人可以告诉我怎么了吗?

page.evaluate executes your function in the page context, not in the PhantomJS context. page.evaluate在页面上下文中而不是在PhantomJS上下文中执行函数。 So, everything that uses console will be printed (and will be visible) only for current Web Page instance. 因此,仅在当前Web Page实例中,使用console所有内容都将被打印(并且将是可见的)。

To redirect the console output, you must use onConsoleMessage callback. 要重定向console输出,必须使用onConsoleMessage回调。

var url = 'http://www.google.com/';
var page = require('webpage').create();

page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.open(url, function () {
    page.injectJs('jquery.min.js');
    page.evaluate(function () {
        console.log($('title').text());
    });
    phantom.exit()
});

Reference: onConsoleMessage 参考: onConsoleMessage

Seem like you're missing # to target element by id : 似乎您缺少#id定位元素:

console.log($('#title').text());
// -----       ^ add here

if title is a class then you can use . 如果title是一个类,则可以使用. :

console.log($('.title').text());

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

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