macabeus
macabeus

Reputation: 4572

Get text from alert in websites

I have the test page:

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

I want get the text of alert when click at button, then I use

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)

But, in the last line, I get erro:

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

Why? How to fix it?

Upvotes: 2

Views: 630

Answers (1)

alecxe
alecxe

Reputation: 473853

There is an open issue at the GhostDriver (webdriver for PhantomJS) issue tracker:

Here is a working workaround (prints 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)

Upvotes: 4

Related Questions