Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 使用类从div的子元素中提取文本?_Ruby_Nokogiri - Fatal编程技术网

Ruby 使用类从div的子元素中提取文本?

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

我有一个小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
  # 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