How to handle alerts with Python?
<p>I wuold like to handle alerts with Python. What I wuold like to do is:</p>

<ul>
<li>open a url</li>
<li>submit a form or click some links</li>
<li>check if an alert occurs in the new page</li>
</ul>

<p>I made this with Javascript using PhantomJS, but I would made even with Python.
Here is the javascript code:</p>

<p>file test.js:</p>

<pre><code>var webPage = require('webpage');
var page = webPage.create();

var url = 'http://localhost:8001/index.html'

page.onConsoleMessage = function (msg) {
    console.log(msg);
}    
page.open(url, function (status) {                
    page.evaluate(function () {
        document.getElementById('myButton').click()       
    });        
    page.onConsoleMessage = function (msg) {
        console.log(msg);
    }    
    page.onAlert = function (msg) {
        console.log('ALERT: ' + msg);
    };    
    setTimeout(function () {
        page.evaluate(function () {
            console.log(document.documentElement.innerHTML)
        });
        phantom.exit();
    }, 1000);
});
</code></pre>

<p>file index.html</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt;
    &lt;title&gt;&lt;/title&gt;
    &lt;meta charset="utf-8" /&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form&gt;
        &lt;input id="username" name="username" /&gt;
        &lt;button id="myButton" type="button" value="Page2"&gt;Go to Page2&lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

&lt;script&gt;
    document.getElementById("myButton").onclick = function () {
        location.href = "page2.html";
    };
&lt;/script&gt;
</code></pre>

<p>file page2.html</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt;
    &lt;title&gt;&lt;/title&gt;
    &lt;meta charset="utf-8" /&gt;
&lt;/head&gt;
&lt;body onload="alert('hello')"&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>This works; it detects the alert on page2.html.
Now I made this python script:</p>

<p>test.py</p>

<pre><code>import requests
from test import BasicTest
from selenium import webdriver
from bs4 import BeautifulSoup   

url = 'http://localhost:8001/index.html'    

def main():
    #browser = webdriver.Firefox()
    browser = webdriver.PhantomJS()
    browser.get(url)
    html_source = browser.page_source
    #browser.quit()    
    soup = BeautifulSoup(html_source, "html.parser")
    soup.prettify()    
    request = requests.get('http://localhost:8001/page2.html')
    print request.text    
    #Handle Alert    
if __name__ == "__main__":
    main();
</code></pre>

<p>Now, how can I check if an alert occur on page2.html with Python? First I open the page index.html, then page2.html.
I'm at the beginning, so any suggestions will be appreciate.</p>

<p>p.s.
I also tested webdriver.Firefox() but it is extremely slow.
Also i read this question : <a href="http://stackoverflow.com/questions/19003003/check-if-any-alert-exists-using-selenium-with-python">Check if any alert exists using selenium with python</a></p>

<p>but it doesn't work (below is the same previous script plus the solution suggested in the answer).</p>

<pre><code>.....    
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

....

def main():
    .....
    #Handle Alert
    try:
        WebDriverWait(browser, 3).until(EC.alert_is_present(),
                                        'Timed out waiting for PA creation ' +
                                        'confirmation popup to appear.')

        alert = browser.switch_to.alert()
        alert.accept()
        print "alert accepted"
    except TimeoutException:
        print "no alert"

if __name__ == "__main__":
    main();
</code></pre>

<p>I get the error : "selenium.common.exceptions.WebDriverException: Message: Invalid Command Method.."</p>

<p>PhantomJS uses GhostDriver to implement the WebDriver Wire Protocol, which is how it works as a headless browser within Selenium. </p>

<p>Unfortunately, GhostDriver does not currently support Alerts. Although it looks like they would like help to implement the features:</p>

<p><a href="https://github.com/detro/ghostdriver/issues/20" rel="nofollow">https://github.com/detro/ghostdriver/issues/20</a></p>

<p>You could possibly switch to the javascript version of PhantomJS or use the Firefox driver within Selenium.</p>

<pre><code>from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException

if __name__ == '__main__':
    # Switch to this driver and switch_to_alert will fail.
    # driver = webdriver.PhantomJS('&lt;Path to Phantom&gt;')
    driver = webdriver.Firefox()
    driver.set_window_size(1400, 1000)
    driver.get('http://localhost:8001/page2.html')

    try:
        driver.switch_to.alert.accept()
        print('Alarm! ALARM!')
    except NoAlertPresentException:
        print('*crickets*')
</code></pre>

python selenium selenium-webdriver phantomjs alert