我正在尝试使用 Watir 和 PhantomJS 与没有 JQuery 的网站进行交互。
browser = Watir::Browser.new :phantomjs, :args => ['--ignore-ssl-errors=yes']
browser.goto 'http://putlocker.is/'
browser.execute_script(
"var the_script = document.createElement('script');
the_script.setAttribute('src','http://code.jquery.com/jquery-1.11.0.min.js');
document.body.appendChild(the_script);"
)
browser.execute_script('$("div").hide();')
使用 Firefox 而不是 PhantomJS 它工作正常 - JQuery 加载到页面上,我可以使用 JQuery 管理元素。但是 PhantomJS 引发了这个错误:
{"errorMessage":"Can't find variable: $","request":{"headers":{"Accept":"application/json","Accept-Encoding":"gzip;q=1.0,deflate;q=0.6,identity;q=0.3","Connection":"close","Content-Length":"41","Content-Type":"application/json; charset=utf-8","Host":"127.0.0.1:8910","User-Agent":"Ruby"},"httpVersion":"1.1","method":"POST","post":"{\"script\":\"$(\\"div\\").hide();\",\"args\":[]}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/84f7d6d0-7035-11e4-a8b8-85c94f571d8e/execute"}} (ReqHand)
我想这个问题与这个问题有某种关系:Can't find variable - PhantomJS .但是如何更改 Watir 代码使其正常工作呢?
最佳答案
PhantomJS 的行为似乎与 Firefox 不同。可能是 PhantomJS 更快,也可能是 PhantomJS 不等待脚本下载。无论哪种情况,您都需要等待脚本加载。您当然可以等待固定的时间,但最好等待适当的时间。
browser.execute_script(injectScript)
Watir::Wait.until { browser.execute_script("return !!window.jQuery") }
browser.execute_script('$("div").hide();')
关于javascript - 将脚本添加到 DOM 后,JQuery 无法在带有 PhantomJS 的 Watir 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027777/