访问Nokogiri元素儿童

时间:2016-09-23 03:42:16

标签: ruby nokogiri

在解析html表时,我能够将表的第一行作为Nokogiri元素。

2.2.1 :041 > pp content[1]; nil
#(Element:0x3feee917d1e0 {
  name = "tr",
  children = [
    #(Element:0x3feee917cfd8 {
      name = "td",
      attributes = [
        #(Attr:0x3feee917cf74 { name = "valign", value = "top" })],
      children = [
        #(Element:0x3feee917ca60 {
          name = "a",
          attributes = [
            #(Attr:0x3feee917c9fc {
              name = "href",
              value = "/cgi-bin/own-disp?action=getowner&CIK=0001513362"
              })],
          children = [ #(Text "Maestri Luca")]
          })]
      }),
    #(Text "\n"),
    #(Element:0x3feee917c150 {
      name = "td",
      children = [
        #(Element:0x3feee917d794 {
          name = "a",
          attributes = [
            #(Attr:0x3feee9179fb8 {
              name = "href",
              value = "/cgi-bin/browse-edgar?action=getcompany&CIK=0001513362"
              })],
          children = [ #(Text "0001513362")]
          })]
      }),
    #(Text "\n"),
    #(Element:0x3feee91796a8 {
      name = "td",
      children = [ #(Text "2016-09-04")]
      }),
    #(Text "\n"),
    #(Element:0x3feee9179194 {
      name = "td",
      children = [ #(Text "officer: Senior Vice President, CFO")]
      }),
    #(Text "\n")]
  })
 => nil 

这是行中的内容:

Maestri Luca 0001513362 2016-09-04官员:首席财务官高级副总裁

我需要从Nokogiri元素访问Name,Number,Date和Title。

一种方法如下:

2.2.1 :042 > pp content[1].text; nil
"Maestri Luca\n0001513362\n2016-09-04\nofficer: Senior Vice President, CFO\n"

但是,我正在寻找一种单独访问元素的方法,而不是使用换行字符长时间访问。我该怎么办?

1 个答案:

答案 0 :(得分:1)

name, number, date, title = *content[1].css('td').map(&:text)

如果content[1]trcontent[1].css('td')会找到其下的所有td元素,.map(&:text)会为每个td.text调用td *并将其放入一个数组中,我们将其与.append展开,以便我们可以进行多次分配。

(注意:下次请包含原始HTML片段,而不是Nokogiri节点检查结果。)