2016-01-21 79 views
2

我有測試頁:從警報獲取文本在網站

<input type='button' id='button' onclick="alert('foo');" value='My Button' /> 

我希望得到警報的文本時,單擊按鈕,然後我用

from selenium import webdriver 
from selenium.webdriver.common import alert 

phantom = webdriver.PhantomJS() 
phantom.get('/home/macabeus/ApenasMeu/test.html') 
phantom.find_element_by_id('button').click() 
x = alert.Alert(phantom) 
print(x.text) 

但是,在最後一行,我得到錯誤:

ValueError: Expecting value: line 1 column 1 (char 0) 

爲什麼?如何解決它?

回答

3

有一個在GhostDriver一個開放的問題(webdriver的用於PhantomJS)問題跟蹤:

這裏是一個工作的解決方法(打印foo):

from selenium import webdriver 

phantom = webdriver.PhantomJS()  
phantom.get('index.html') 

phantom.execute_script("window.alert = function(msg){ window.msg = msg; };") 

phantom.find_element_by_id('button').click() 

alert_text = phantom.execute_script("return window.msg;") 
print(alert_text) 
+0

我得到相同的錯誤,並且'alert'不可調用 – Macabeus

+0

@Macabeus是的,好點。讓我試着重現這個問題。順便說一句,Firefox中會發生什麼? – alecxe

+0

我還沒有用Firefox進行過測試,因爲我需要使用PhantomJS。這是更快,需要更少的內存 – Macabeus