Module: Watir::XpathLocator

Included in:
Locator
Defined in:
lib/watir-classic/xpath_locator.rb

Instance Method Summary collapse

Instance Method Details

#direct_children(container, elements) ⇒ Object



46
47
48
49
# File 'lib/watir-classic/xpath_locator.rb', line 46

def direct_children container, elements
  return elements if container.is_a?(IE)
  elements.select {|el| el.parent == container}
end

#element_by_css(selector) ⇒ Object

return the first element that matches the css selector



19
20
21
# File 'lib/watir-classic/xpath_locator.rb', line 19

def element_by_css(selector)
  elements_by_css(selector)[0]
end

#element_by_xpath(xpath) ⇒ Object

return the first element that matches the xpath



24
25
26
# File 'lib/watir-classic/xpath_locator.rb', line 24

def element_by_xpath(xpath)
  elements_by_xpath(xpath)[0]
end

#elements_by_css(selector) ⇒ Object

execute css selector and return an array of elements



12
13
14
15
16
# File 'lib/watir-classic/xpath_locator.rb', line 12

def elements_by_css(selector)
  xmlparser_document_object # Needed to ensure Nokogiri has been loaded
  xpath = Nokogiri::CSS.xpath_for(selector)[0]
  elements_by_xpath(xpath)
end

#elements_by_xpath(xpath) ⇒ Object

execute xpath selector and return an array of elements



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/watir-classic/xpath_locator.rb', line 29

def elements_by_xpath(xpath)
  doc = xmlparser_document_object
  current_tag = @container.is_a?(IE) ? "body" : @container.tag_name

  doc.xpath(xpath).reduce([]) do |elements, element|
    absolute_xpath_parts = element.path.split("/")
    first_tag_position = absolute_xpath_parts.index(current_tag) || absolute_xpath_parts.index("html") + 1
    element_xpath_parts = absolute_xpath_parts[first_tag_position..-1]
    elements << element_xpath_parts.reduce(@container.page_container) do |container, tag|
      tag_name, index = tag.split(/[\[\]]/)
      index = index ? index.to_i - 1 : 0
      specifiers = {:tag_name => [tag_name]}
      direct_children(container, container.send(:elements, specifiers))[index]
    end.ole_object
  end
end

#xmlparser_document_objectObject



4
5
6
7
8
9
# File 'lib/watir-classic/xpath_locator.rb', line 4

def xmlparser_document_object
  @xml_parser_doc ||= begin
                        require 'nokogiri'
                        Nokogiri.parse("<html>#{@container.html}</html>")
                      end
end