使用 HTTPUnit getElementsByClass() 的好方法是什么?

发布于 2024-10-06 10:19:13 字数 874 浏览 0 评论 0原文

我尝试过

HTMLElement[] focused = response.getElementsWithAttribute("class", "focused");

,希望它能找到

<span class="focused">Submit</span>

其他内容,但我得到的只是一个空数组。

谷歌对我没有任何帮助。

所以。如果您是我,并且想通过类名获取 HTMLElements 数组,您会使用什么?

编辑:

我希望有帮助的来源

public class ExampleIT extends TestCase {
    private final String BASE = "http://localhost:8080/preview.htm?";

    @Test
    public void testFocusedArePresent() throws MalformedURLException, SAXException, IOException {
        WebConversation conversation = new WebConversation();
        WebResponse response = conversation.getResponse(BASE + "template=Sample");
        HTMLElement[] focused = response.getElementsWithAttribute("class", "focused");
        assertTrue(focused.length > 0);
    }
}

I tried

HTMLElement[] focused = response.getElementsWithAttribute("class", "focused");

I was hoping it would find

<span class="focused">Submit</span>

among others, but all I get back is an empty array.

Google has been no help to me.

So. If you were me and you wanted to get an array of HTMLElements by class name, what would you use?

Edit:

The source

public class ExampleIT extends TestCase {
    private final String BASE = "http://localhost:8080/preview.htm?";

    @Test
    public void testFocusedArePresent() throws MalformedURLException, SAXException, IOException {
        WebConversation conversation = new WebConversation();
        WebResponse response = conversation.getResponse(BASE + "template=Sample");
        HTMLElement[] focused = response.getElementsWithAttribute("class", "focused");
        assertTrue(focused.length > 0);
    }
}

I hope that helps.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

极致的悲 2024-10-13 10:19:13

getElementsWithAttribute 对我有用。或者,您可以尝试迭代 DOM,查找具有指定类属性的元素。这是一些示例代码:

    Document doc = response.getDOM();
    List<Node> result = new ArrayList<Node>();
    NodeList list = doc.getElementsByTagName("*");
    for(int i = 0 ; i < list.getLength() ; i++){
        Node n = list.item(i).getAttributes().getNamedItem("class");
        if(n!=null && "focused".equals(n.getNodeValue())){
            result.add(n); 
        }
    }

getElementsWithAttribute works for me. Alternatively, you can try iterating over the DOM, looking for an element with a specified class attribute. Here is some sample code:

    Document doc = response.getDOM();
    List<Node> result = new ArrayList<Node>();
    NodeList list = doc.getElementsByTagName("*");
    for(int i = 0 ; i < list.getLength() ; i++){
        Node n = list.item(i).getAttributes().getNamedItem("class");
        if(n!=null && "focused".equals(n.getNodeValue())){
            result.add(n); 
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文