【问题标题】:Extract text retaining links using Nokogiri使用 Nokogiri 提取文本保留链接
【发布时间】:2017-05-05 14:52:42
【问题描述】:

如何在保留<a> 标签的同时从关注<p> 中提取文本

<p>
  Some <a href="http://somewhere.com">link</a> going somewhere.
  <ul>
    <li><a href="http://lowendbox.com/">Low end</a></li>
  </ul>
  Some trailing text.
</p>

预期输出:

Some <a href="http://somewhere.com">link</a> going somewhere.
<a href="http://lowendbox.com/">Low end</a>
Some trailing text.

我能想到的唯一解决方案是覆盖 Nokogiri text 方法并递归 children,希望有一些简单的解决方案。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请参阅“minimal reproducible example”和 Jon Skeet 的“Writing the perfect question”。我们需要看到你努力的证据。您是否寻找解决方案?如果是这样,你发现了什么,为什么没有帮助?你写代码了吗?如果不是,为什么?如果是这样,您编写的演示您遇到的问题的最少代码是多少。否则,您似乎并没有尝试并希望我们为您解决问题,这不是 SO 的目的。
  • 你想做的事情并不难,但也并不简单。您必须获取&lt;p&gt; 标记的inner_html,然后提升内部&lt;a&gt; 以替换&lt;ul&gt;。我不会为您编写代码,因为它在 SO 和 Nokogiri 教程中的多个答案中并且您没有表现出努力。向我们展示您写的内容,我们会付出更多努力来帮助您。

标签: ruby web-scraping nokogiri mechanize


【解决方案1】:

您不能在 p 内有 ul 这样的任何尝试将其解析为 html4 或 html5 的尝试都会失败。剩下的正则表达式可以很容易地解决这个问题:

str = <<EOF
<p>
  Some <a href="http://somewhere.com">link</a> going somewhere.
  <ul>
    <li><a href="http://lowendbox.com/">Low end</a></li>
  </ul>
  Some trailing text.
</p>
EOF
puts str.gsub(/<\/?(p|ul|li)>/,'')

#  Some <a href="http://somewhere.com">link</a> going somewhere.
#
#    <a href="http://lowendbox.com/">Low end</a>
#
#  Some trailing text.

【讨论】:

    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多