【问题标题】:Using ruby and nokogiri to parsing HTML using HTML comments as markers使用 ruby​​ 和 nokogiri 使用 HTML 注释作为标记来解析 HTML
【发布时间】:2010-11-13 14:12:46
【问题描述】:

如何使用 ruby​​ 从包含这些行的表中提取信息?是否可以使用 nokogiri 检测 cmets?

<!-- Begin Topic Entry 4134 --> 
    <tr> 
        <td align="center" class="row2"><image src='style_images/ip.boardpr/f_norm.gif' border='0'  alt='New Posts' /></td> 
        <td align="center" width="3%" class="row1">&nbsp;</td> 
        <td class="row2"> 
            <table class='ipbtable' cellspacing="0"> 
                <tr> 

<td valign="middle"><alink href='http://www.xxx.com/index.php?showtopic=4134&amp;view=getnewpost'><image src='style_images/ip.boardpr/newpost.gif' border='0'  alt='Goto last unread' title='Goto last unread' hspace=2></a></td> 

                    <td width="100%"> 
                    <div style='float:right'></div> 
                    <div> <alink href="http://www.xxx.com/index.php?showtopic=4134&amp;hl=">EXTRACT LINK 1</a>  </div> 
                    </td> 
                </tr> 
            </table> 
            <span class="desc">EXTRACT DESCRIPTION</span> 
        </td> 
        <td class="row2" width="15%"><span class="forumdesc"><alink href="http://www.xxx.com/index.php?showforum=19" title="Living">EXTRACT LINK 2</a></span></td> 
        <td align="center" class="row1" width='10%'><alink href='http://www.xxx.com/index.php?showuser=1642'>Mr P</a></td> 
        <td align="center" class="row2"><alink href="javascript:who_posted(4134);">1</a></td> 
        <td align="center" class="row1">46</td> 
        <td class="row1"><span class="desc">Today, 12:04 AM<br /><alink href="http://www.xxx.com/index.php?showtopic=4134&amp;view=getlastpost">Last post by:</a> <b><alink href='http://www.xxx.com/index.php?showuser=1649'>underft</a></b></span></td> 
    </tr> 
<!-- End Topic Entry 4134 -->
-->

【问题讨论】:

  • 你能提供一个更具体的例子吗?具体输入输出?
  • @Michael:有示例文本,它出现在预览中,但不在问题中。现在修复它...

标签: html ruby parsing comments nokogiri


【解决方案1】:

尝试改用xpath

html_doc = Nokogiri::HTML("<html><body><!-- Begin Topic Entry 4134 --></body></html>") 
html_doc.xpath('//comment()')

【讨论】:

  • 我相信这应该是公认的解决方案,因为它是最直接的。
【解决方案2】:

您可以实现 Nokogiri SAX Parser。这比乍看起来要快。你会得到元素、属性和评论的事件。

在您的解析器中,您应该记住状态,例如 @currently_interested = true 以知道要记住哪些部分,哪些不。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2018-05-03
    • 2013-04-02
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多