Get Elements By Attributes

爷,独闯天下 提交于 2019-12-24 02:25:45

问题


i will be short.

As far as i know watir library provides two methods for getting html elements.

Almost for each element (div, button, table, li, etc) watir provides two methods:

. One is the 'singular' method which gets only one specific element. For example:

watir_instance.div(:id,'my_div_id')
watir_instance.link(:href,'my_link_href')
watir_instance.button(:class =>'my_button_class', :index => 4)

These methods will only retrieve A SINGLE ELEMENT. Thats ok...

. The second is the 'plural' method that will retrieve ALL the elements of the watir instance

watir_instance.divs
watir_instance.links
watir_instance.buttons

But as far as i know watir doesn't provide a method to get more than one element giving certain conditions.

For example... If i want to flash all the links with id:my_link_id it would be very easy to do something like this:

watir_instance.divs(:id, 'my_link_id').each do |link|
  link.flash
end

With hpricot this task is very easy... but if your aim is not to parse i couldn't find a Watir Method that does what i want.

Hope you can understand me...

Cheers, Juan!!


回答1:


Juan,

your script has several problems:

  • You say you want to flash all links, but then you use watir_instance.divs. It should be watir_instance.links
  • you pass arguments to divs method: watir_instance.divs(:id, 'my_link_id'). It should be just watir_instance.divs

Your example is also strange:

i want to flash all the links with id:my_link_id

As far as I know, id should be unique at the page.

So, here are different examples:

1) Flash all links on this page:

require "watir"
b = Watir::IE.start "http://stackoverflow.com/questions/1434697"
b.links.each do |link|
  link.flash
end

2) Flash all links on this page that have questions in URL (bonus: scroll the page so the link that is flashed is visible):

require "watir"
b = Watir::IE.start "http://stackoverflow.com/questions/1434697"
b.links.each do |link|
  if link.href =~ /questions/
    link.document.scrollintoview
    link.flash
  end
end


来源:https://stackoverflow.com/questions/1434697/get-elements-by-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!