I have a ul
with child links that are buried a few levels down, what is the best way to extract them with xpath or watir?
browser.element(xpath: "//h3/following-sibling::ul[1]//a").html
and
browser.element(xpath: "//h3/following-sibling::ul[1]").a.href
will get me the first the first link, but not all of them. How can you extract all links?
I've tried browser.element(xpath: "//h3/following-sibling::ul[1]//*[@href]")
but it also only gives me the first element
If you call the #as
or #links
method on the ul
element, Watir will return all child links, regardless of how many levels down they are. From there, you can iterate over the links to get the href.
browser.element(xpath: "//h3/following-sibling::ul[1]").as.map(&:href)
#=> ["href1", "href2", "etc"]
If you want to avoid XPath, you can also do:
browser.h3.following_sibling(tag_name: 'ul').as.map(&:href)