Rubyx Rubyx - 1 month ago 9
Ruby Question

Getting text in strong with Watir

I'm trying to get the text inside

<strong>
.

Html code is:

<div>
<a class="business-link"></a>

<a class="business-link">
<strong>Text</strong>
</a>

<a class="business-link"></a>
</div>


There are multiple
business-link
class on the page, I need only the one who contain a
strong
.
There are multi
strong
on the page, but only one inside a
business-link
class.

I tried:

browser.a(:class => /business-link/).strong.text


and

browser.link(:class => /business-link/).strong.text


But when trying:

unable to locate element, using {:tag_name=>"strong"} (Watir::Exception::UnknownObjectException)


Any idea?

Answer

The problem with browser.a(:class => /business-link/).strong.text is that it finds the first link with class "business-link" and then, within that link, looks for the strong element. The first link is not the one with the strong element. What you really want to tell Watir is to find the first link that also contains a strong element.

You could create a collection of the links and iterate through them until you find a strong element:

business_links = browser.links(class: 'business-link')
business_link = business_links.find { |link| link.strong.exist? }
business_link.strong.text # or simply `business_link.text`
#=> "Text"

If you are comfortable with :css (or :xpath) locators, this can be more succinctly written as:

browser.strong(css: 'a.business-link > strong').text
#=> "Text"