7

问题: GhostDriver API 还不支持警报处理。目前有一个可接受的解决方法,即将您自己的 javascript 注入将处理警报并为您存储其文本的页面。

我在通过 python webdriver 绑定使用此解决方法时遇到问题。这可能与我对javascript的新手级理解有关。

这是我尝试使用的解决方法的一个示例: https ://github.com/detro/ghostdriver/issues/20#issuecomment-15641983

我正在使用一个显示警报的公共网站,以使这更简单:http ://www.tizag.com/javascriptT/javascriptalert.php

这是我的代码:

from selenium import webdriver

button_xpath = "/html/body/table[3]/tbody/tr/td[2]/table/tbody/tr/td/div[4]/form/input"

js = """
(function () {
var lastAlert = undefined;
window.alert = function (message) {
    lastAlert = message;
};
window.getLastAlert = function () {
    var result = lastAlert;
    lastAlert = undefined;
    return result;
};
}());
"""

driver = webdriver.PhantomJS()
driver.get('http://www.tizag.com/javascriptT/javascriptalert.php')
driver.execute_script("window.alert = %s" % js)
driver.find_element_by_xpath(button_xpath).click()
#exception just occured
driver.execute_script("return window.getLastAlert && window.getLastAlert();")

例外是:

WebDriverException: Message: u'Error Message => \'Click failed: TypeError: \'undefined\' is not a function (evaluating \'alert(\'Are you sure you want to give us the deed to your house?\')\')\'\n caused by Request => {"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:41752","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\\"sessionId\\": \\"0eaf7680-9897-11e2-b375-55b9cb6ceb0f\\", \\"id\\": \\":wdc:1364578560610\\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click","directory":"/","path":"/click","relative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/click","queryKey":{},"chunks":["click"]},"urlOriginal":"/session/0eaf7680-9897-11e2-b375-55b9cb6ceb0f/element/%3Awdc%3A1364578560610/click"}' ; Screenshot: available via screen 

我是一个JS菜鸟。我希望有人能指出我正确的方向。

4

2 回答 2

10

一个简单的解决方案是重写 window.alert 方法以将参数输出到全局变量。

使用覆盖函数定义 js 注入变量:

js = """
window.alert = function(message) {
lastAlert = message;
}
"""

然后只需通过 python 中的 execute_script 调用传递 js 变量,如下所示:

driver.execute_script("%s" % js)

然后,当它全部运行后,您可以在全局 lastAlert 上执行 return:

driver.execute_script("return lastAlert")
于 2013-04-05T16:26:38.383 回答
4

这是一些解决方法。

将其用于稍后会发出警报的每个重新加载的页面。

driver.execute_script("window.confirm = function(){return true;}");

这适用于 Selenium/Splinter 中的 PhantomJS。

在此处查看更多参考。

于 2015-09-02T17:46:06.113 回答