2016-01-21 83 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