2016-08-24 30 views
0

我正在尝试使用Nokogiri的CSS方法从我的HTML中获取一些名称。使用Nokogiri的CSS方法获取alt标签中的所有元素

这是HTML的一个例子:

<section class="container partner-customer padding-bottom--60"> 
    <div> 
     <div> 
      <a id="technologies"></a> 
      <h4 class="center-align">The Team</h4> 
     </div> 
    </div> 
    <div class="consultant list-across wrap"> 
     <div class="engineering"> 
      <img class="" src="https://v0001.jpg" alt="Person 1"/> 
      <p>Person 1<br>Founder, Chairman &amp; CTO</p> 
     </div> 
     <div class="engineering"> 
      <img class="" src="https://v0002.png" alt="Person 2"/></a> 
      <p>Person 2<br>Founder, VP of Engineering</p> 
     </div> 
     <div class="product"> 
      <img class="" src="https://v0003.jpg" alt="Person 3"/></a> 
      <p>Person 3<br>Product</p> 
     </div> 
     <div class="Human Resources &amp; Admin"> 
      <img class="" src="https://v0004.jpg" alt="Person 4"/></a> 
      <p>Person 4<br>People &amp; Places</p> 
     </div> 
     <div class="alliances"> 
      <img class="" src="https://v0005.jpg" alt="Person 5"/></a> 
      <p>Person 5<br>VP of Alliances</p> 
     </div> 

我在我的people.rake文件至今如下:

staff_site = Nokogiri::HTML(open("https://www.website.com/company/team-all")) 
    all_hands = staff_site.css("div.consultant").map(&:text).map(&:squish) 

我有一点点麻烦中的所有元素alt=""标签(人的名字),因为它嵌套在几个div下。

当前,使用div.consultant,它获取所有名称+角色,即Person 1Founder, Chairman; CTO,而不是alt=中的人名。

我怎么能简单地得到alt内的元素?

+0

请阅读“[mcve]”。您的HTML无效;请确保结束标签位于正确的位置。如果没有那些Nokogiri会把它们放在它认为应该是的地方,它们可能会与你的想法大相径庭。你的预期产出是多少? –

回答

1

您所需的输出不清晰,HTML被破坏。

开始与此:

require 'nokogiri' 

doc = Nokogiri::HTML('<html><body><div class="consultant"><img alt="foo"/><img alt="bar" /></div></body></html>') 
doc.search('div.consultant img').map{ |img| img['alt'] } # => ["foo", "bar"] 

上的css输出使用text是不是一个好主意。 css返回一个NodeSet。 text对一个节点集结果中的所有文本被连接起来,其结果往往是错位的文本内容,迫使你弄清楚如何再次拉开它,这,到底是可怕的代码:

doc = Nokogiri::HTML('<html><body><p>foo</p><p>bar</p></body></html>') 
doc.search('p').text # => "foobar" 

此行为是记录在NodeSet#text

获取所有包含节点的内部文本对象

相反,使用text(AKA inner_textcontent)对各个节点,导致该节点的确切内容,那你则可以根据需要加入:

返回此节点

doc.search('p').map(&:text) # => ["foo", "bar"] 

请参阅“How to avoid joining all text from Nodes when scraping”的内容也。