2013-08-06 4 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> 

내가 노코 기리에 새로 온 사람, 그리고 내가 궁금 해서요 .nbaBreakingNews div 내의 링크에서 텍스트를 추출하는 방법 (예 : NBA에서 생방송) :

enter image description here

그리고 내 템플릿에 표시하십시오.

(지금은 클래스와 ID가있는 HTML 태그에서 텍스트를 추출하는 방법 만 알고 있습니다.) 이들 섹션

답변

1

a 요소 것이다 :

클래스 nbaBreakingNewscv으로 요소의 하위 요소 a 어떤 수단
data.css('.nbaBreakingNewscv a') 

. 해당 문자의 a 텍스트를 표시하려면 다음을 입력하십시오.

data.css('.nbaBreakingNewscv a').each do |a| 
    puts a.text 
end 
관련 문제