如何使用Python处理警报?

2024-04-24 09:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 打开url
  • 提交表单或单击某些链接
  • 检查新页面中是否出现警报

我使用Javascript使用PhantomJS制作了这个,但即使使用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);
});

文件index.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脚本:

测试.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: Message: Invalid Command Method.."


Tags: fromimportbrowserhttpurlmainhtmlselenium
1条回答
网友
1楼 · 发布于 2024-04-24 09:24:45

PhantomJS使用GhostDriver来实现WebDriver-Wire协议,这就是它在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*')

相关问题 更多 >