問題:用selenium+phantomjs 模擬登陸,網頁用JavaScript的alert(“登陸成功”)彈出框,但是用switch_to_alert().accept()報錯,不可執行命令。
目標代碼:<script language="javascript">alert('********************');</script>
顯示錯誤:
File "sy.py", line 112, in <module>
Pop123= Pop_up.text
File "C:\Python27\lib\site-packages\selenium\webdriver\common\alert.py", line 69, in text
return self.driver.execute(Command.GET_ALERT_TEXT)["value"]
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 165, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: Invalid Command Method - {"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:59198","User-Agent":"Python http auth"},"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/95d315d0-ce94-11e7-8d72-c1b9396af0ea/alert_text"}
搜到的解決方案:
phantomjs是沒有界面的,無法j解析動態的JS,所以對alert也是無法直接彈出的,故phantomjs以該函數回調在page在執行過程中的alert事件。
python沒有對應phentomjs特殊的庫,所以需要調用JS。
python selenium官方已不再對phentomjs提供支持。現在主打火狐瀏覽器 和 谷歌瀏覽器 請盡量更換
一 、python調用Js
r = driver.execute_script("return newsJason")
print r
二、Js里面的方法 時間較忙未進行測試對錯
page.onAlert = function(msg) {}
driver.execute_script("window.confirm = function(msg) { return true; }");