Ruby-如何使用Nokogiri检索div之后的文本

时间:2019-04-28 17:44:08

标签: ruby nokogiri

我正在尝试从下面的代码(目标代码)中检索日期和时间信息。我可以输入班级名称,但不能输入日期和时间。

class = events.at_css('div.classTitle b').text
date = events.at_css('.classTitle') ["eventTime"]
time = events.at_css('.classTime span')

p class
p date
p time

我得到班级名称,但日期和时间为零

目标代码

<div class="classTitle"><b>Astronomy 101</b></div>

<div class="classTime">

Friday, May 3, 2019<span class="smalltype">&nbsp;at</span>&nbsp;7:00PM</div>

<br>

1 个答案:

答案 0 :(得分:1)

Node#content方法:

https://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Node#content-instance_method

index.html

<div class="classTitle"><b>Astronomy 101</b></div>

<div class="classTime">

Friday, May 3, 2019<span class="smalltype">&nbsp;at</span>&nbsp;7:00PM
</div>

<br>

test.rb

require 'nokogiri'

events = Nokogiri::HTML(open('index.html'))
date, time = events.at_css('div.classTime').content.strip.split('at')

puts date     #=> Friday, May 3, 2019
puts time     #=> 7:00PM