【问题标题】:How to get text after or before certain tags using Nokogiri如何使用 Nokogiri 在某些标签之后或之前获取文本
【发布时间】:2017-04-25 02:01:15
【问题描述】:

我有一个 HTML 文档,如下所示:

<root><template>title</template>
<h level="3" i="3">Something</h>
<template element="1"><title>test</title></template>
# one
# two
# three
# four
<h level="4" i="5">something1</h>
some random test
<template element="1"><title>test</title></template>
# first
# second
# third
# fourth
<template element="2"><title>testing</title></template>

我要提取:

# one
# two 
# three
# four
# first
# second
# third
# fourth
</root>

换句话说,我想要“&lt;template element="1"&gt;&lt;title&gt;test&lt;/title&gt;&lt;/template&gt; 之后和之后开始的下一个标签之前的所有文本。”

我可以使用'//root/text()' 获取根目录之间的所有文本,但如何获取特定标签前后的所有文本?

【问题讨论】:

  • 我不认为它有一个选择器(我当然可能是错的),也许你可以使用 SAX 方法
  • 你能详细说明一下萨克斯的方法吗?
  • sax 是一种一次导航一个标签的方法,而不是使用选择器引用特定标签,但经过一些研究我认为你会面临同样的问题,也就是说,你可以根文本,而不是标签和另一个标签之间的文本,我猜你需要从 '//root/text()' 中减去所有其他标签,或者(如果可以的话)更改模板格式以使用类似

    的东西该中间文本的标记。

  • 这不是 HTML,而是 XML。此外,示例 XML 不会验证,因为您的关闭 &lt;root&gt; 节点位于示例文本之后。

标签: ruby nokogiri


【解决方案1】:

这似乎有效:

require 'nokogiri'

xml = '<root>
    <template>title</template>
    <h level="3" i="3">Something</h>
    <template element="1">
        <title>test</title>
    </template>
    # one
    # two
    # three
    # four
    <h level="4" i="5">something1</h>
    some random test
    <template element="1">
        <title>test</title>
    </template>
    # first
    # second
    # third
    # fourth
    <template element="2">
        <title>testing</title>
    </template>
</root>
'

doc = Nokogiri::XML(xml)
text = (doc / 'template[@element="1"]').map{ |n| n.next_sibling.text.strip.gsub(/\n  +/, "\n") }
puts text
# >> # one
# >> # two
# >> # three
# >> # four
# >> # first
# >> # second
# >> # third
# >> # fourth

【讨论】:

    【解决方案2】:

    我很确定 krusty.ar 是正确的,没有内置的方法可以实现这一点。如果您愿意,您可以一一删除根标签内的所有标签。这是一个 hack,但它有效:

    doc = Nokogiri::HTML(open(url)) # or Nokogiri::HTML.parse(File.open(file_path))
    doc.xpath('//template').remove
    doc.xpath('//h').remove
    doc
    

    这给出了您在发布的 HTML 中寻找的结果。

    【讨论】:

    • 这会在结果中间留下“一些随机测试”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多