0

I am trying to do a 2 stage xpath selection with WatirWebdriver, first to find the elements within a container and then to find specific info from each element:

# Select all elements of interest
browser.divs(xpath: '/html/body/ul/li[@class="thing"]').each do |pannel|
  # Select info from each element
  panel.element(xpath: '//h1[@class="thing_title"]/a')
end

The problem is that the second xpath select does not search children of the given node. It searches the entire page and selects the first match - so you get the same info of the first match every time. I found one solution is to give it a complete path like so:

# Select info from each element
panel.element(xpath: 'div/div[2]/div[1]/div/h1/a')

But the path is not necessarily the same every time, which breaks things.

Is there way to search children of the given node only, without specifying the complete path?

1 Answer 1

1

The problem is that the inner XPath says to search for the h1 element anywhere in the document. To only search within the context of the current node, you need to tell the XPath by starting with a .:

panel.element(xpath: './/h1[@class="thing_title"]/a')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Justin! I was misled by the w3school's docs "// - Selects nodes in the document from the current node that match the selection no matter where they are" but im guessing they mean it in a query like /first_node//rest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.