2016-08-24 31 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」的內容也。