javascript PhantomJS; 单击一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15739263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:55:05  来源:igfitidea点击:

PhantomJS; click an element

javascriptclickphantomjs

提问by user984003

How do I click an element in PhantomJS?

如何单击 PhantomJS 中的元素?

page.evaluate(function() {
    document.getElementById('idButtonSpan').click();  
});

This gives me an error "undefined is not a function..."

这给了我一个错误“未定义不是函数......”

If I instead

如果我改为

 return document.getElementById('idButtonSpan');

and then print it,

然后打印出来

then it prints [object object], so the element does exist.

然后它打印 [object object],因此该元素确实存在。

The element acts as a button, but it's actually just a span element, not a submit input.

该元素充当按钮,但它实际上只是一个 span 元素,而不是提交输入。

I was able to get this button click to work with Casper, but Casper had other limitations so I'm back to PhantomJS.

我能够点击此按钮以与 Casper 一起使用,但 Casper 有其他限制,所以我又回到了 PhantomJS。

采纳答案by user984003

.click()is not standard. You need to create an event and dispatch it:

.click()不是标准的。您需要创建一个事件并调度它:

function click(el){
    var ev = document.createEvent("MouseEvent");
    ev.initMouseEvent(
        "click",
        true /* bubble */, true /* cancelable */,
        window, null,
        0, 0, 0, 0, /* coordinates */
        false, false, false, false, /* modifier keys */
        0 /*left*/, null
    );
    el.dispatchEvent(ev);
}

回答by TheCloudlessSky

Alternatively to @torazaburo's response, you could stub HTMLElement.prototype.clickwhen running in PhantomJS. For example, we use PhantomJS + QUnit to run our tests and in our qunit-config.jswe have something like this:

替代@torazaburo 的回应,您可以HTMLElement.prototype.click在 PhantomJS 中运行时存根。例如,我们使用 PhantomJS + QUnit 来运行我们的测试,qunit-config.js我们有这样的东西:

if (window._phantom) {
  // Patch since PhantomJS does not implement click() on HTMLElement. In some 
  // cases we need to execute the native click on an element. However, jQuery's 
  // $.fn.click() does not dispatch to the native function on <a> elements, so we
  // can't use it in our implementations: $el[0].click() to correctly dispatch.
  if (!HTMLElement.prototype.click) {
    HTMLElement.prototype.click = function() {
      var ev = document.createEvent('MouseEvent');
      ev.initMouseEvent(
          'click',
          /*bubble*/true, /*cancelable*/true,
          window, null,
          0, 0, 0, 0, /*coordinates*/
          false, false, false, false, /*modifier keys*/
          0/*button=left*/, null
      );
      this.dispatchEvent(ev);
    };
  }
}

回答by stovroz

It's not pretty, but I've been using this to allow me to use jQuery for the selection:

它并不漂亮,但我一直在使用它来允许我使用 jQuery 进行选择:

var rect = page.evaluate(function() {
    return $('a.whatever')[0].getBoundingClientRect();
});
page.sendEvent('click', rect.left + rect.width / 2, rect.top + rect.height / 2);

but you can always replace $(s)[0]with document.querySelector(s)if not using jQuery.

但是如果不使用 jQuery,你总是可以替换$(s)[0]document.querySelector(s)

(It does rely on the element being in view mind, i.e. your viewportSize.height is big enough).

(它确实依赖于视图中的元素,即您的 viewportSize.height 足够大)。

回答by Jobins John

Hope the following method will be useful. It worked for me in version 1.9

希望下面的方法有用。它在 1.9 版中对我有用

page.evaluate(function(){
    var a = document.getElementById("spr-sign-in-btn-standard");
    var e = document.createEvent('MouseEvents');
    e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
    waitforload = true;
});

This worked for me. Hope this will be useful for others also

这对我有用。希望这对其他人也有用

回答by HappyCoder888

use simple JavaScript with evaluate, something like this:

使用简单的 JavaScript 和evaluate,如下所示:

page.evaluate(function() {
    document.getElementById('yourId').click();
});

回答by sshaw

With 1.9.2this worked for me, click handlers were triggered:

有了1.9.2这个工作对我来说,被触发的点击处理程序:

var a = page.evaluate(function() {
    return document.querySelector('a.open');
});

page.sendEvent('click', a.offsetLeft, a.offsetTop);

回答by user984003

I never was able to directly click the element. Instead, I looked at the html to find what function was called with onclick, and then called that function.

我从来没有能够直接点击元素。相反,我查看了 html 以查找使用 onclick 调用的函数,然后调用该函数。

回答by Artjom B.

Double clicks are also possible with PhantomJS.

PhantomJS 也可以双击。

Recommended

受到推崇的

This is adapted from the answerof stovrozand triggers a native dblclickincluding the mousedown, mouseupand clickevents (two of each).

这是改编自stovroz的答案,并触发了一个本地事件,包括,和事件(每个两个)。dblclickmousedownmouseupclick

var rect = page.evaluate(function(selector){
    return document.querySelector(selector).getBoundingClientRect();
}, selector);
page.sendEvent('doubleclick', rect.left + rect.width / 2, rect.top + rect.height / 2);

Other ways

其他方法

The following two ways only trigger the dblclickevent, but not the other events that should precede it.

以下两种方式只触发dblclick事件,而不触发应该在它之前的其他事件。

Adapted from this answerof torazaburo:

改编自这个答案torazaburo

page.evaluate(function(selector){
    var el = document.querySelector(sel);
    var ev = document.createEvent("MouseEvent");
    ev.initMouseEvent(
        'dblclick',
        true /* bubble */, true /* cancelable */,
        window, null,
        0, 0, 0, 0, /* coordinates */
        false, false, false, false, /* modifier keys */
        0 /*left*/, null
    );
    el.dispatchEvent(ev);
}, selector);

Adapted from this answerof Jobins John:

改编自这个答案Jobins约翰

page.evaluate(function(selector){
    var el = document.querySelector(sel);
    var e = document.createEvent('MouseEvents');
    e.initMouseEvent('dblclick', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    el.dispatchEvent(e);
}, selector);

Full test script

完整的测试脚本

回答by GracefulCode

Document.querySelector(element).click() works when using Phantomjs 2.0

Document.querySelector(element).click() 在使用 Phantomjs 2.0 时有效

click: function (selector, options, callback) {
    var self = this;
    var deferred = Q.defer();
    options = options || {timeout:1000}; 
    setTimeout(function () { 
        self.page.evaluate(function(targetSelector) {
            $(document).ready(function() {
                document.querySelector(targetSelector).click();
            }) ;
        }, function () {
                deferred.resolve();
        }, selector);
    }, options.timeout);
    return deferred.promise.nodeify(callback);
},

回答by Jiayuan Zhang

The easiest way is using jQuery.

最简单的方法是使用jQuery。

page.evaluate(function() {
  page.includeJs("your_jquery_file.js", function() {
    page.evaluate(function() {
      $('button[data-control-name="see_more"]').click();
    });
  });
});