2013-08-06 50 views
0

我有一個小西納特拉應用:從提取一個div一類的子元素的文本?

app.rb:

get '/' do 
    # the first two lines are lifted directly from our previous script 
    url = "http://www.nba.com/" 
    data = Nokogiri::HTML(open(url)) 

    # this line has only be adjusted slightly with the inclusion of an ampersand 
    # before concerts. This creates an instance variable that can be referenced 
    # in our display logic (view). 
    @headlines = data.css('#nbaAssistSkip') 
    @top_stories = data.css('#nbaAssistSkip') 

    # this tells sinatra to render the Embedded Ruby template /views/shows.erb 
    erb :shows 
end 

show.erb:

<!DOCTYPE HTML> 
<html lang="en-US"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Nokogiri App</title> 
</head> 
<body> 
    <div> 
    <h2><%= @headlines %></h2> 
    <p><%= @top_stories %></p> 
    </div> 
</body> 
</html> 

我是新來引入nokogiri,我想知道我怎麼能.nbaBreakingNews專區內提取的鏈接的文本(例如住在NBA ...):

enter image description here

而且在我的模板顯示它們。

(現在,我只知道如何從HTML標籤處理類和ID中提取文本)。

回答

1

在那些部分中的a元件將是:

data.css('.nbaBreakingNewscv a') 

這意味着任何a元件,其從元件下降與nbaBreakingNewscv類。要顯示那些a元素的文字,你應該這樣做:

data.css('.nbaBreakingNewscv a').each do |a| 
    puts a.text 
end 
相關問題