2013-03-27 58 views
4

我刚刚开始与nokogiri从网站抓取信息,无法弄清楚如何完成以下操作。我有一些HTML代码,我想刮:Nokogiri :: HTML和Ruby的Web Scraping - 如何获得输出到数组?

<div class="compatible_vehicles"> 
    <div class="heading"> 
    <h3>Compatible Vehicles</h3> 
    </div><!-- .heading --> 
    <ul> 
      <li> 
     <p class="label">Type1</p> 
     <p class="data">All</p> 
    </li> 
    <li> 
     <p class="label">Type2</p> 
     <p class="data">All</p> 
    </li> 
    <li> 
     <p class="label">Type3</p> 
     <p class="data">All</p> 
    </li> 
    <li> 
     <p class="label">Type4</p> 
     <p class="data">All</p> 
    </li> 
    <li> 
     <p class="label">Type5</p> 
     <p class="data">All</p> 
    </li> 
    </ul> 
    </div><!-- .compatible_vehicles --> 

而且我设法让我的屏幕上输出我想这一点:

i = 0 
    doc.css('div > .compatible_vehicles > ul > li').each do |item| 
     label = item.at_css(".label").text 
     data = item.at_css(".data").text 
    print "#{label} - #{data}" + ',' 
    end 
    i += 1 

这给了我这样一个列表:类型1 - 屏幕上的全部,类型2 - 全部,类型3 - 全部,类型4 - 全部,类型5 - 全部, 。

现在我想在数组中获取这个值,以便能够将它保存到CSV文件中。我尝试了几件事情,但大部分尝试都得到'无法将字符串转换为数组'的错误。 希望有人能帮助我解决这个问题!

回答

2

与HTML开始:

html = ' 
<div class="compatible_vehicles"> 
    <div class="heading"> 
     <h3>Compatible Vehicles</h3> 
    </div><!-- .heading --> 
    <ul> 
     <li> 
     <p class="label">Type1</p> 
     <p class="data">All</p> 
     </li> 
     <li> 
     <p class="label">Type2</p> 
     <p class="data">All</p> 
     </li> 
     <li> 
     <p class="label">Type3</p> 
     <p class="data">All</p> 
     </li> 
     <li> 
     <p class="label">Type4</p> 
     <p class="data">All</p> 
     </li> 
     <li> 
     <p class="label">Type5</p> 
     <p class="data">All</p> 
     </li> 
    </ul> 
</div><!-- .compatible_vehicles --> 
' 

与引入nokogiri分析它和循环在<li>标签让他们<p>标签内容:

require 'nokogiri' 

doc = Nokogiri::HTML(html) 
data = doc.search('.compatible_vehicles li').map{ |li| 
    li.search('p').map { |p| p.text } 
} 

返回数组的数组:

=> [["Type1", "All"], ["Type2", "All"], ["Type3", "All"], ["Type4", "All"], ["Type5", "All"]] 

从那里你应该能够插入到电子邮件CSV类的xamples,并让它在没有问题的情况下工作。

现在,你的代码比较输出到田里屏幕这样的:

data.map{ |a| a.join(' - ') }.join(', ') 
=> "Type1 - All, Type2 - All, Type3 - All, Type4 - All, Type5 - All" 

所有我需要做的就是puts,它会正确打印。

考虑返回有用的数据结构真的很重要。在Ruby中,哈希和数组非常有用,因为我们可以遍历它们并将它们按摩成许多形式。从阵列阵列中创建一个哈希值将是微不足道的:

Hash[data] 
=> {"Type1"=>"All", "Type2"=>"All", "Type3"=>"All", "Type4"=>"All", "Type5"=>"All"} 

这会使查找变得非常简单。

+0

太棒了!谢谢您的帮助! – user2215918 2013-03-27 16:24:56