【问题标题】:Extracting the text from the child elements of a div with a class?从带有类的div的子元素中提取文本?
【发布时间】:2013-08-07 09:11:44
【问题描述】:

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

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 div 中的链接中提取文本(例如 Live on NBA...):

并将它们显示在我的模板中。

(目前我只知道如何从带有类和ID的html标签中提取文本)。

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    这些部分中的a 元素将是:

    data.css('.nbaBreakingNewscv a')
    

    这意味着任何a 元素都继承自类nbaBreakingNewscv 的元素。要显示这些 a 元素的文本,您可以:

    data.css('.nbaBreakingNewscv a').each do |a|
      puts a.text
    end
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 2023-03-25
      • 1970-01-01
      • 2019-06-22
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      相关资源
      最近更新 更多