有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试使用HTMLUnit保存html文本框元素时出现java类型转换异常

我一直在尝试创建一个Java类来对一个网站进行测试,但我遇到了一个障碍,那就是试图使用HTMLUnit API向该网站输入用户名和密码。以下是我试图基于的html部分:

            <div class="inner_contain">

                <table cellpadding="2" cellspacing="1" border="0" align="center">
                    <tr>
                        <form name="frm1" action="blank" onSubmit="defaultSubmit(); return false;" method="post">
                            <Td align="right"><strong>Username:</strong></Td>
                            <td><input type="text" maxlength="20" class="login_input" /></td>
                        </form>
                    </tr>

                    <tr>
                        <form name="frm2" action="blank" onSubmit="defaultSubmit(); return false;" method="post">
                            <Td align="right"><strong>Password:</strong></Td>
                            <td><input type="password" maxlength="20"
                                class="login_input" /></td>
                        </form>
                    </tr>

                    <tr>
                        <td colspan="2" align="center"><input type="button" value="Login" class="submit" onclick="javascript:LoginSubmit('Login')" /></td>
                    </tr>
                </table>

            </div>

下面是该部分的代码片段:

final HtmlForm usernameForm = page.getElementByName("frm1");

final HtmlTextInput usernameInput = (HtmlTextInput) usernameForm.getByXPath("//input[@class='login_input' and @type='text']");

但无论是否使用HtmlTextInput,我仍然会遇到以下错误:

java.util.ArrayList cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlTextInput

如果您能帮助提交用户凭据,我们将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    你只需要阅读the API doc

    public List<?> getByXPath(String xpathExpr)
    

    Evaluates the specified XPath expression from this node, returning the matching elements

    注意返回类型和复数形式的用法。如果要获取单个元素,则获取返回列表的第一个元素,或使用^{}

    public <X> X getFirstByXPath(String xpathExpr)
    

    Evaluates the specified XPath expression from this node, returning the first matching element, or null if no node matches the specified XPath expression.

    阅读文档时,一切都简单得多