Mrityunjeyan S Mrityunjeyan S - 4 years ago 135
Ruby Question

Watir: How do i get inner_html of multiple span, with same class name

I am using this code, to grab the

of the span class.

weather = browser.span(:class => "_Xbe kno-fv").inner_html
puts weather

However, Multiple
exists with the same class, in the page. How do I retrieve all of them at once?

I am trying to get the information relating to weather from this page

weather = browser.span(:class => "_Xbe kno-fv").text
puts weather

This above code, prints, the text but not consistently. I beleive, since multiple elements exists with the same class or the information is dynamic and hence? I am not sure. Is there a way to get this?

Result in the first run

| Search |
| Bangalore | 741 km²

Result in the second run

| Search |
| Bangalore | 17°C, Wind E at 3 km/h, 69% Humidity

Answer Source

The element that you are targeting is contained within a <div> with a unique data attribute. I'd advise using that approach:

require 'watir'    
b = :chrome
b.goto "" 

puts b.div(:data_attrid => "kc:/location/citytown:current weather").text
#=> Weather: 59°F (15°C), Wind S at 2 mph (3 km/h), 83% Humidity

For reference--as @JustinKo demonstrates--watir can use data attributes as locators with some minor tweaks.

Sidenote: running automated searches against Google may be a violation of their Terms of Service, and you may find yourself blocked. You should investigate if you can use one of their many APIs to harvest this data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download