代码之家  ›  专栏  ›  技术社区  ›  d3llafr33

如何在java中使用HtmlUnitDriver处理警报?

  •  0
  • d3llafr33  · 技术社区  · 8 年前

    我正在尝试使用HtmlUnitDriver处理警报事件,但我有一些问题,我想了解原因。 下面是java代码:

    HtmlUnitDriver browser = new HtmlUnitDriver(true);
    browser.get("http://localhost:8001/index.html");
    browser.findElementById("myButton").click();
    
    try {
        WebDriverWait wait = new WebDriverWait(browser, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = browser.switchTo().alert();
        alert.accept();
        System.out.println("ALERT");
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.out.println("NO ALERT");
    }
    String htmlContent = browser.getPageSource();
    System.out.println(htmlContent);
    
    browser.close();    
    

    这是html代码: 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 id="form1">
            <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>   
    

    第2.html页

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>Page2</title>
        <meta charset="utf-8" />
    </head>
    <body onload="myfunction('hello2')">
        <p id="result"></p>
    </body>
    </html>
    <script>
        function myfunction(data) {
            document.getElementById('result').innerHTML = data
        }
    </script>
    

    控制台中的输出为:

    NO ALERT
    <?xml version="1.0" encoding="UTF-8"?>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>
          Page2
        </title>
        <meta charset="utf-8"/>
      </head>
      <body onload="myfunction('hello2')">
        ?
    
    
        <p id="result">
          hello2
        </p>
        <script>
    //<![CDATA[
    
        function myfunction(data) {
            document.getElementById('result').innerHTML = data
        }
    
    //]]>
        </script>
      </body>
    </html>
    

    看一下输出,它似乎与源代码有点不同,对此我有几个问题。 为什么没有检测到page2.html上的警报? 为什么有一些额外的字符,例如“?”和“//<![CDATA[”?如何避免?

    我正在尝试处理警报,而且我还处于起步阶段,所以任何建议都将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Community CDub    8 年前

    p#result 的innerHTML转换为“hello2”。

    至于额外的字符,我不太确定。 This answer 可能会对生成的CDATA内容有所帮助。