Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.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
Html 仅解析外部元素_Html_Ruby_Nokogiri - Fatal编程技术网

Html 仅解析外部元素

Html 仅解析外部元素,html,ruby,nokogiri,Html,Ruby,Nokogiri,我正在用Nokogiri编写一个刮刀,我想刮刀一个大的HTML文件 目前,我正在刮一张大桌子;下面是一个小片段: <table id="rptBidTypes__ctl0_dgResults"> <tr> <td align="left">S24327</td> <td> Airfield Lighting <div> <div&g

我正在用Nokogiri编写一个刮刀,我想刮刀一个大的HTML文件

目前,我正在刮一张大桌子;下面是一个小片段:

<table id="rptBidTypes__ctl0_dgResults">
    <tr>
      <td align="left">S24327</td>

      <td>
        Airfield Lighting

        <div>
          <div>
          <table cellpadding="5px" border="2" cellspacing="1px" width="100%" bgcolor=
          "black">
              <tr>
                <td bgcolor="white">Abstract:<br />
                This project is for the purchase and delivery, of various airfield
                lighting, for a period of 36 months, with two optional 1 year renewals,
                in accordance with the specifications, terms and conditions specified in
                the solicitation.</td>
              </tr>
            </table>
          </div>
        </div>
      </td>
    </tr>
</table>
不幸的是,这对我不起作用。我只想提取
S24327
,但我得到的是每个表单元格的内容。如何仅提取第一个
td
的内容


请记住,在此表下,有许多表行采用相同的格式。

问题在于您的搜索匹配了两种不同的内容:直接嵌套在id为
的表中的
标记和嵌套在父表中的表中的
标记。当您在
文档[1..-1]
中循环时,实际上选择的是第二个
标记,而不是第一个

要仅选择直接子标签,请使用:

document = doc.search("table#rptBidTypes__ctl0_dgResults > tr")
然后,您可以通过以下方式获取
标记的文本:

document.css('td')[0].text   #=> "S24327"

问题是您的搜索匹配了两种不同的内容:直接嵌套在id为rptBidTypes的表中的
标记,以及嵌套在父表中的表中的
标记。当您在
文档[1..-1]
中循环时,实际上选择的是第二个
标记,而不是第一个

要仅选择直接子标签,请使用:

document = doc.search("table#rptBidTypes__ctl0_dgResults > tr")
然后,您可以通过以下方式获取
标记的文本:

document.css('td')[0].text   #=> "S24327"

第一次td的内容将是:

doc.at("table#rptBidTypes__ctl0_dgResults td").text

第一次td的内容将是:

doc.at("table#rptBidTypes__ctl0_dgResults td").text

在CSS中,
table tr
表示
tr
表下的任何位置,包括嵌套表。但是
table>tr
意味着
tr
必须是
表的直接子项

此外,您似乎只需要单元格值,因此不需要迭代。这将为您提供所有此类单元格(每行的第一个):


在CSS中,
table tr
表示
tr
表下的任何位置,包括嵌套表。但是
table>tr
意味着
tr
必须是
表的直接子项

此外,您似乎只需要单元格值,因此不需要迭代。这将为您提供所有此类单元格(每行的第一个):


css
实际上给出了所有td,与
search
相同
at
只给出第一个。如果你只想要第一个
td
,不要使用
[0]
,正如@pguardiario指出的那样,使用
at
css
实际上给出了所有td,与
搜索
一样
at
只给出第一个。如果你只想要第一个
td
,不要使用
[0]
,使用
at
,正如@pguardiario所指出的。OP不想要第一个,他想要所有匹配的数字。嗯,我刚把问题再读一遍,他似乎想要第一个。你说得对。我假设他想要他例子中的第一个
td
,其他人都喜欢。我仍然认为是这样的,但我可能读得太多了。OP不想要第一个,他想要所有匹配的数字。嗯,我刚刚又读了一遍问题,他似乎要求第一个。你说得对。我假设他想要他例子中的第一个
td
,其他人都喜欢。我仍然认为是这样,但我可能读得太多了。顺便说一句,我会将变量“document”重命名为“rows”。“rows”更好,但“trs”最精确。您想在文档中列出所有此类代码吗?顺便说一句,我会将变量“document”重命名为“rows”。“rows”更好,但是“trs”是最精确的。您想在文档中列出所有这些代码吗?