简体   繁体   中英

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

I am using this code, to grab the inner_html of the span class.

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

However, Multiple inner_html 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? 4

Result in the first run

Examples:
  | Search    |
  | Bangalore |  741 km²

Result in the second run

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

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 = Watir::Browser.new :chrome
b.goto "https://www.google.com/?gfe_rd=cr&ei=w7-YWN75OsyAoAPK_oDYBQ#q=bangalore" 

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.

I'm not sure if it is the cause of your problem, but one significant issue is that you are using multiple class values when a class locator can only accept one:

Don't do this: browser.span(:class => "_Xbe kno-fv")

Do this: browser.span(css: "._Xbe.kno-fv")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM