2011-11-21 100 views
0

我在使用Mechanize試圖獲得下面的結果的博客。將我的想法變成代碼邏輯主要有困難。我假設我需要結合搜索子句並遍歷html,並在找到匹配時打印出來。新的使用Rails和任何建議將會有所幫助。機械化使用2搜索刮?

期望的結果:

  • first_title
    • first_image_url
    • second_image_url
  • second_title
    • first_image_url
    • second_image_url

代碼:

require 'rubygems' 
require 'mechanize' 

url = 'http://blog.something.com/' 
mech = Mechanize.new 
page = mech.get(url) 

page.search('h2').each do |h2| 
    puts h2.inner_text 
end 

imgs = page.search('img[src]').map{|src| src['src']} 
puts imgs 

課程的代碼權生產:

  • first_title
  • second_title
  • third_title
  • ...
  • first_image_url
  • second_image_url
  • first_image_url
  • ...

回答

1

假設圖像從H2的後裔,你可以這樣做:

page.search('h2').each do |h2| 
    puts h2.inner_text 
    h2.css('img').each do |img| 
    puts img['src'] 
    end 
end 
+0

如果'img'不下降從'h2'結束?這是一個不同的div。我試過這個替換你的'h2.css''page.search('img')。each | img |放img ['src'] end' – TheRealDK

+0

在這種情況下,您將製作一些xpath表達式來獲取圖像。這取決於標記。 – pguardiario