代码之家  ›  专栏  ›  技术社区  ›  thomas

Ruby Nokogiri解析HTML表

  •  4
  • thomas  · 技术社区  · 15 年前

    我使用的是机械化/nokogiri,需要解析以下HTML字符串。 有人能帮我使用xpath语法来完成这项工作吗,或者其他任何可行的方法?

    <table>
      <tr class="darkRow">
        <td>
          <span>
            <a href="?x=mSOWNEBYee31H0eV-V6JA0ZejXANJXLsttVxillWOFoykMg5U65P4x7FtTbsosKRbbBPuYvV8nPhET7b5sFeON4aWpbD10Dq">
                <span>4242YP</span>
            </a>
          </span>
        </td>
        <td>
          <span>Subject of Meeting</span>
        </td>
        <td>
          <span>
            <span>01:00 PM</span> 
            <span>Nov 11 2009</span> 
            <span>America/New_York</span>
          </span>
        </td>
        <td>
          <span>30</span>
        </td>
        <td>
          <span>
            <span>example@email.com</span>
          </span>
        </td>
        <td>
            <span>39243368</span>
        </td>
      </tr>
      .
      .
      .
      <more table rows with the same format>
    </table>
    

    我要这个作为输出

    "4242YP","Subject of Meeting","01:00 PM Nov 11 2009 America/New_York","30","example@email.com", "39243368"
    .
    .
    .
    <however many rows exist in the html table>
    
    2 回复  |  直到 15 年前
        1
  •  4
  •   JasonTrue    15 年前

    像这样?

    items=doc.xpath('//tr').map {|row| row.xpath('.//span/text()').select{|item| item.text.match(/\w+/)}.map {|item| item.text} }
    

    返回: =>[“4242YP”,“会议主题”,“01:00 PM”,“2009年11月11日”,“美国/纽约”,“30”,“example@email.com”,“39243368”],[“abcdefg”]

    选择仅包括以单词字符开头的跨距(例如,排除某些跨距的空白)。您可能需要为您的特定案例细化“选择”过滤器。

    我添加了一个包含abcdefg的范围的极简行,这样您就可以看到嵌套数组。

        2
  •  0
  •   Carl Smotricz    15 年前

    以下是XSL的一部分,用于转换输入,如果您有XSL转换器:

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    
    <xsl:template match="/">
       <xsl:apply-templates select="//tr"/>
    </xsl:template>
    
    <xsl:template match="tr">
       "<xsl:value-of select="td/span/a/span"/>","<xsl:value-of select="td[position()=2]/span"/>","<xsl:value-of select="td[position()=3]/span/span[position()=1]"/>"
    </xsl:template>
    
    </xsl:stylesheet>
    

    产生的输出如下:

    "4242YP","Subject of Meeting","01:00 PM"
    "4242YP","Subject of Meeting","01:00 PM"
    

    (我复制了你的第一行表格)。

    XSLSelect位可以让您很好地了解需要什么样的xpath输入来获取其余的部分。