【问题标题】:How to click on selectbox options using PhantomJS如何使用 PhantomJS 单击选择框选项
【发布时间】:2015-09-24 21:57:49
【问题描述】:

有一个页面testkrok.org.ua 具有一致的参数选择。因此,我需要在 5 个相互依赖的选择框的每个选项上创建一系列 5 次点击。

document.querySelector('select.se1')[3]
document.querySelector('select.se2')[1]
document.querySelector('select.se3')[1]
document.querySelector('select.se4')[1]
document.querySelector('select.se5')[3]

重定向到带有测试的页面。

但是在第一次单击后拍摄的快照上没有出现第二个面板? 也许我没有击中元素?

var page = require('webpage').create();
page.open('https://testkrok.org.ua', function(status) {
    console.log("Status: " + status);
    if(status === "success") {
        page.evaluate(function() {
            var theEvent = document.createEvent("MouseEvent");
            theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            var element = document.querySelector('select.se1')[3];
            element.dispatchEvent(theEvent);
        });
    }
    setTimeout( function() {
        page.render('snapshot.png');
        phantom.exit()
    }, 5000);
});

【问题讨论】:

  • 如果我理解正确,您想单击选择框选项。我不认为这些实际上是不可点击的。此外,您可能需要在点击后稍等片刻。
  • @ArtjomB。添加setTimeout 5 秒,但什么也没有

标签: javascript click phantomjs html-select


【解决方案1】:

您不能单击(触发单击事件)选择框的选项。您需要更改所选选项,然后更改trigger a change event。例如:

var sel = document.querySelector('select.se1');
sel.selectedIndex = 2;
var event = new UIEvent("change", {
    "view": window,
    "bubbles": true,
    "cancelable": true
});
sel.dispatchEvent(event);

你可以把它打包成一个函数

function selectOption(selector, optionIndex) {
    page.evaluate(function(selector, optionIndex){
        var sel = document.querySelector(selector);
        sel.selectedIndex = optionIndex;
        var event = new UIEvent("change", {
            "view": window,
            "bubbles": true,
            "cancelable": true
        });
        sel.dispatchEvent(event);
    }, selector, optionIndex);
}

然后你可以一个接一个地调用它

selectOption("select.se1", 2);
selectOption("select.se2", 0);
selectOption("select.se3", 0);
...

你明白了。如果选择框的onChange 事件需要远程数据,例如通过 AJAX,那么您将需要在调用之间等待。使用静态等待时间(参见以下示例)或使用waitFor()

setTimeout(function(){
    selectOption("select.se1", 2);
}, 1000);
setTimeout(function(){
    selectOption("select.se2", 0);
}, 2000);
setTimeout(function(){
    selectOption("select.se3", 0);
}, 3000);
...

【讨论】:

  • 在此更改后,快照上有选定字段,但第二个选择标签未出现,它返回错误TypeError: 'undefined' is not an object (evaluating 'document.getElementsByTagName('option')[2].parentElement')
  • 即使在 Firefox 控制台中也无法正常工作,这是一些 JS 魔法
  • 是的,触发更改事件是必要的。我更新了我的答案。
  • 谢谢,这工作。也许你甚至知道如何推送document.querySelector('p.start_button')
  • 如果您的意思是触发点击,那么您已经使用 MouseEvent 在您的问题中尝试过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 2021-11-07
  • 2014-07-11
  • 2012-10-06
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
相关资源
最近更新 更多