【问题标题】:How to handle alerts with Python?如何使用 Python 处理警报?
【发布时间】:2016-09-30 11:00:59
【问题描述】:

我很喜欢用 Python 处理警报。我最喜欢做的是:

  • 打开一个网址
  • 提交表单或点击一些链接
  • 检查新页面是否出现警报

我使用 PhantomJS 使用 Javascript 制作了这个,但我什至会使用 Python 制作。

这里是javascript代码:

文件 test.js:

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);
});

文件索引.html

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

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

文件 page2.html

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

这行得通;它检测到 page2.html 上的警报。 现在我制作了这个 python 脚本:

test.py

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();

现在,如何使用 Python 检查 page2.html 上是否出现警报?首先我打开页面 index.html,然后打开 page2.html。 我才刚开始,所以任何建议都将不胜感激。

附言 我还测试了 webdriver.Firefox() 但它非常慢。 我也读过这个问题:Check if any alert exists using selenium with python

但它不起作用(下面是相同的先前脚本加上答案中建议的解决方案)。

.....    
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();

我得到了错误:

“selenium.common.exceptions.WebDriverException:消息:无效 命令方法..”

【问题讨论】:

    标签: python selenium selenium-webdriver phantomjs alert


    【解决方案1】:

    PhantomJS 使用 GhostDriver 来实现 WebDriver Wire Protocol,这就是它在 Selenium 中作为无头浏览器工作的方式。

    很遗憾,GhostDriver 目前不支持警报。虽然看起来他们需要帮助来实现这些功能:

    https://github.com/detro/ghostdriver/issues/20

    您可以切换到 PhantomJS 的 javascript 版本或使用 Selenium 中的 Firefox 驱动程序。

    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('<Path to Phantom>')
        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*')
    

    【讨论】:

    • 嗨!感谢你的回答。我试图运行您的解决方案,但它不起作用。它打开一个空白页,没有任何反应。我错过了什么吗?
    • 脚本使用 Python 3.5 解释器运行,您使用的是这个吗?我建议将 'main': 下的代码和 import 语句复制并粘贴到您自己的脚本中。如果运行正确,它应该会打开一个指向您的 URL 的 Firefox 窗口,并将两条消息之一打印到控制台。
    • 我使用的是 python 2.7。我切换到 python 3.5 但结果是一样的。我也听从了你的建议。我正在使用硒 v.2.53.6
    • 当所有其他方法都失败时,调试:) 打开你的 python 控制台并逐行执行。 (跳过 if name == 'main': 行)。我预计这是 Python 看不到 webdriver 或 webdriver 无法连接到 URL 的问题。脚本真正做的就是打开 URL,尝试切换到警报,然后打印到控制台。
    猜你喜欢
    • 2022-09-23
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多