Rubyx Rubyx - 3 months ago 25
Ruby Question

Getting text in strong with Watir

I'm trying to get the text inside


Html code is:

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

<a class="business-link">

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

There are multiple
class on the page, I need only the one who contain a
There are multi
on the page, but only one inside a

I tried:

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

and => /business-link/).strong.text

But when trying:

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

Any idea?


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: ' > strong').text
#=> "Text"