Skip to content
Browse files

Merge pull request #287 from philou/master

Search links and images through css or xpath
  • Loading branch information...
2 parents d3b9ce2 + 076aeb1 commit e0ac8748ec318de012c83910da2df7e5c14fd176 @leejarvis leejarvis committed Feb 9, 2013
Showing with 65 additions and 6 deletions.
  1. +17 −6 lib/mechanize/element_matcher.rb
  2. +48 −0 test/test_mechanize_page.rb
View
23 lib/mechanize/element_matcher.rb
@@ -6,14 +6,14 @@ def #{plural}_with criteria = {}
criteria = if String === criteria then
{:name => criteria}
else
- criteria.map do |k, v|
- k = :dom_id if k.to_sym == :id
- k = :dom_class if k.to_sym == :class
- [k, v]
- end
+ Hash[criteria.map do |k, v|
+ k = :dom_id if k.to_sym == :id
+ k = :dom_class if k.to_sym == :class
+ [k, v]
+ end]
end
- f = #{plural}.find_all do |thing|
+ f = select_#{plural}(criteria.delete(:search)).find_all do |thing|
criteria.all? do |k,v|
v === thing.send(k)
end
@@ -28,6 +28,17 @@ def #{singular}_with criteria = {}
f
end
+ def select_#{plural} selector
+ if selector.nil? then
+ #{plural}
+ else
+ nodes = search(selector)
+ #{plural}.find_all do |element|
+ nodes.include?(element.node)
+ end
+ end
+ end
+
alias :#{singular} :#{singular}_with
CODE
end
View
48 test/test_mechanize_page.rb
@@ -143,5 +143,53 @@ def test_parser_no_attributes
assert_kind_of Nokogiri::HTML::Document, page.root
end
+ def test_search_links
+ page = html_page <<-BODY
+<html>
+ <meta>
+ <head><title></title>
+ <body>
+ <span id="spany">
+ <a href="b.html">b</a>
+ <a href="a.html">a</a>
+ </span>
+ <a href="6.html">6</a>
+ </body>
+</html>
+ BODY
+
+ links = page.links_with(:search => "#spany a")
+
+ assert_equal 2, links.size
+ assert_equal "b.html", links[0].href
+ assert_equal "b", links[0].text
+
+ assert_equal "a.html", links[1].href
+ assert_equal "a", links[1].text
+ end
+
+ def test_search_images
+ page = html_page <<-BODY
+<html>
+ <meta>
+ <head><title></title>
+ <body>
+ <img src="a.jpg" class="pretty">
+ <img src="b.jpg">
+ <img src="c.png" class="pretty">
+ </body>
+</html>
+ BODY
+
+ images = page.images_with(:search => "//img[@class='pretty']")
+
+ assert_equal 2, images.size
+ assert_equal "pretty", images[0].dom_class
+ assert_equal "a.jpg", images[0].src
+
+ assert_equal "pretty", images[1].dom_class
+ assert_equal "c.png", images[1].src
+ end
+
end

0 comments on commit e0ac874

Please sign in to comment.
Something went wrong with that request. Please try again.