在幻像.js中确认警报窗口

confirm alert window in phantom.js

本文关键字:窗口 确认 js      更新时间:2023-09-26

我有这个功能,可以找到按钮并单击它,但是在该警报出现后,我需要使用幻影进行确认.js

function() {
  page.evaluate(function() {
    $('.item-list clicked').first().find($('.comment-delete')).find('a').click();
  })
}

也许我可以模拟调用警报而立即单击的功能? 或使用函数等待等待此警报?(不太可能,等待仅等待 DOM 对象,我认为是这样)

我也找不到另一个帮助我回答这个问题的 stackoverflow 答案,但基本上你可以注入一个 javascript 函数来确认警报弹出窗口:

这是我的python webdriver实现:

def example_js_confirmation( self ):
    js_confirm = 'window.confirm = function(){return true;}'    # .js function to confirm a popup
    self.execute_javascript( js_confirm )
    self.find_by_id( 'submit' ).click()
    self.execute_javascript( 'return window.confirm' )  # trigger the injected js that returns true (virtually click OK)

它在某人的待办事项列表中 =) :硒所需功能 - 设置句柄PhantomJS驱动程序的警报

我所知,Phantom.JS是无头的。您唯一能做的就是通过以下方式获取警报的上下文

window.onAlert = function(alertText){
    ...
   }

但我认为仅此而已。不能以编程方式关闭(常规)或呈现(在 Phantom.JS 中)警报。

一些来源:
* 使用 Phantom 渲染 JavaScript 警报.JS
* 以编程方式关闭警报

"

确认警报"是一个令人困惑的短语,因为Javascript同时提供了alert(显示带有确定按钮的消息)和confirm(显示确定和取消按钮),并且不清楚你的意思是哪一个。

至少 PhantomJS 2.x 的行为就像它在alert框上单击"确定",在confirm框上单击"取消"。

如果您想在confirm框上单击"确定"而不是"取消",只要您不担心在加载过程中弹出confirm框,就可以调用execute_javascript覆盖window.confirm以返回true,这将在您的execute_javascript有机会干预之前进行处理。 如果你也想抓住这些,我能想到的最好的办法就是修补PhantomJS源代码或通过上游代理注入JS。

我做到了:

// 1) override window.alert
page.evaluate(function(){
  window.alert = function(msg){
    window.callPhantom({alert: msg}); // will call page.onCallback()
    return true; // will "close the alert"
  };
});
// 2) re-bind to onAlert()
page.onCallback = function(obj) {
  page.onAlert(obj.alert); // will trigger page.onAlert()
};