Ruby 使用类从div的子元素中提取文本?
我有一个小Sinatra应用程序: app.rb:Ruby 使用类从div的子元素中提取文本?,ruby,nokogiri,Ruby,Nokogiri,我有一个小Sinatra应用程序: 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
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
<!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>
show.erb:
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
<!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应用程序
我是Nokogiri的新手,我想知道如何从.nbaBreakingNews
div(例如NBA直播…)中的链接中提取文本:
并在我的模板中显示它们
(现在,我只知道如何从带有类和ID的html标记中提取文本)。这些部分中的
a
元素是:
data.css('.nbaBreakingNewscv a')
这意味着从类为nbaBreakingNewscv的元素派生的任何元素。要显示这些a
元素的文本,请执行以下操作:
data.css('.nbaBreakingNewscv a').each do |a|
puts a.text
end