Watir:如何获得具有相同 class 名称的多个跨度的 inner_html

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

我正在使用此代码来获取跨度 class 的 inner_html

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

但是,页面中存在多个 inner_html 且具有相同的 class。我如何一次检索所有这些?

我正在尝试从这个page

获取有关天气的信息
weather = browser.span(:class => "_Xbe kno-fv").text
puts weather

上面的代码打印了文本但不一致。我相信,因为存在多个具有相同 class 的元素,或者信息是动态的,因此?我不知道。有没有办法得到这个? 4

第一个结果运行

Examples:
  | Search    |
  | Bangalore |  741 km²

第二个结果运行

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

我不确定这是否是你的问题的原因,但一个重要的问题是当 class 定位器只能接受一个时,你使用了多个 class 值:

不要这样做:browser.span(:class => "_Xbe kno-fv")

这样做:browser.span(css: "._Xbe.kno-fv")

您定位的元素包含在具有唯一数据属性的 <div> 中。我建议使用这种方法:

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

供参考——因为@JustinKo demonstrates——watir 可以使用数据属性作为定位器并进行一些小的调整。

旁注:运行 针对 Google 的自动搜索可能违反了他们的服务条款,您可能会发现自己被屏蔽了。您应该调查是否可以使用他们的众多 API 之一来收集这些数据。