0

I have html like so:

<div id="myId">
    <a href="#">
        <div class="name">Item1</div>
        <span class="location">32143|2323</span>
    </a>
    <a href="#">
        <div class="name">Item1</div>
        <span class="location">32143|2323</span>
    </a>
    <a href="#">
        <div class="name">Item1</div>
        <span class="location">32143|2323</span>
    </a>
</html>

Using HtmlUnit for Java, I need to grab the name and location of each anchor. I tried doing a getByXPath to pickup all the anchors, then looping through them with a for and running another getByXpath to get the name in the div. However the individual items in the list are apparently Objects, so I am unable to run a second getByXPath.

I also tried running the first getByXPath using "/a/div[@class='name']" to which I loop through the results which are Objects and I cannot find the proper method for returning the contents of the divs.

Tyler
  • 3,713
  • 6
  • 37
  • 63

1 Answers1

3

If your xpath select element, you can cast the list to the desired type:

List<HtmlElement> divs = (List<HtmlElement>)document.getByXPath("//a/div[@class='name']");
Nicolas Labrot
  • 4,017
  • 25
  • 40
  • But I need only the elements under the div with id=myId, as well, I can't figure out how to get the content out of the freaking element. – Tyler Apr 12 '15 at 12:09
  • You can do too `page.getElementById("myId")`and iterate over the childrens `getChildren()`. If don't understand correctly please explain fully your purpose. – Nicolas Labrot Apr 12 '15 at 12:16
  • For some reason your code is returning 0 results for me: http://pastebin.com/vQ8d1RGv – Tyler Apr 12 '15 at 12:28
  • yes, the xpath does not target any element. The correct xpath should be `//a/div[@class='name']` or maybe better `//a[@href='#']/div[@class='name']` – Nicolas Labrot Apr 12 '15 at 12:29
  • If you add that extra slash in the answer I will accept it when I can – Tyler Apr 12 '15 at 12:33