gpt4 book ai didi

javascript - 如何通过 Python 使用 GhostDriver 处理警报?

转载 作者:太空狗 更新时间:2023-10-29 21:24:38 25 4
gpt4 key购买 nike

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

我在通过 python 网络驱动程序绑定(bind)使用此解决方法时遇到问题。这可能与我对javascript的新手水平理解有关。

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

我正在使用一个演示警报的公共(public)站点,以使其更直接: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();")

异常(exception)情况是:

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 菜鸟。我希望有人能给我指出正确的方向。

最佳答案

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

用覆盖函数定义 js 注入(inject)变量:

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

然后像这样通过 python 中的 execute_script 调用传递 js 变量:

driver.execute_script("%s" % js)

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

driver.execute_script("return lastAlert")

关于javascript - 如何通过 Python 使用 GhostDriver 处理警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15708518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com