phantomjs通过watir-webdriver,不处理javascript警报

时间:2013-10-01 20:51:33

标签: ruby phantomjs watir-webdriver

我正在尝试在网页上自动执行某些任务,其中一部分包括点击一个链接,该链接会显示javascript警报,您必须按“确定”。麻烦的是,当它到达那一点时,它失败并出现以下错误

/Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/remote/http/common.rb:66:in `create_response': unexpected response, code=405, content-type="text/plain" (Selenium::WebDriver::Error::WebDriverError)
Invalid Command Method - Request => {"headers":{"Accept":"application/json","Accept-Encoding":"gzip;q=1.0,deflate;q=0.6,identity;q=0.3","Cache-Control":"no-cache","Connection":"close","Host":"127.0.0.1:8910","User-Agent":"Ruby"},"httpVersion":"1.1","method":"GET","url":"/alert_text","urlParsed":{"anchor":"","query":"","file":"alert_text","directory":"/","path":"/alert_text","relative":"/alert_text","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/alert_text","queryKey":{},"chunks":["alert_text"]},"urlOriginal":"/session/6772bf50-2ad9-11e3-86e7-55e618e30fa2/alert_text"}
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/remote/http/default.rb:66:in `request'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/remote/bridge.rb:634:in `raw_execute'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/remote/bridge.rb:612:in `execute'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/remote/bridge.rb:150:in `getAlertText'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/alert.rb:9:in `initialize'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/target_locator.rb:76:in `new'
    from /Users/username/.gem/ruby/2.0.0/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/target_locator.rb:76:in `alert'
    from /Users/username/.gem/ruby/2.0.0/gems/watir-webdriver-0.6.4/lib/watir-webdriver/alert.rb:93:in `assert_exists'
    from /Users/username/.gem/ruby/2.0.0/gems/watir-webdriver-0.6.4/lib/watir-webdriver/alert.rb:37:in `ok'
    from ./olx:21:in `block in <main>'
    from ./olx:19:in `times'
    from ./olx:19:in `<main>'

在网上搜索,似乎问题可能是related to ghostdriver,也许phantomjs无法做到,但这个概念对我来说似乎有些奇怪(它被称为幻影* js * ,毕竟,警报是非常基本的javascript),但也许我看错了。

使用chrome运行脚本,它可以完美运行。

2 个答案:

答案 0 :(得分:11)

PhantomJS无法正确处理JavaScript存在一个已知问题。 一种解决方法是通过运行以下命令禁用警报框:

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

基本上,您要遵循的步骤是:

  1. 转到页面
  2. 运行上面的命令
  3. 点击“删除”(或触发警报框的任何内容)
  4. 它会自动为您点击“确定”。

答案 1 :(得分:-1)

当然,

在开始行动之前运行它:

browser.execute_script(“window.confirm = function(){return true;}”);

这有助于确认弹出窗口。