【问题标题】:Extract text between HTML tags提取 HTML 标签之间的文本
【发布时间】:2013-05-18 21:39:31
【问题描述】:

我有许多需要从中提取文本的 HTML 文件。如果它都在一行上,我可以很容易地做到这一点,但如果标签环绕或在多行上,我不知道如何做到这一点。这就是我的意思:

<section id="MySection">
Some text here
another line here <br>
last line of text.
</section>

我不关心&lt;br&gt; 文本,除非它有助于环绕文本。我想要的区域始终以“MySection”开头,然后以&lt;/section&gt; 结尾。我想结束的是这样的:

Some text here  another line here  last line of text.

我更喜欢 vbscript 或命令行选项(sed?),但我不知道从哪里开始。有什么帮助吗?

【问题讨论】:

    标签: vbscript sed text-files command-line-tool


    【解决方案1】:

    通常您会为此使用 Internet Explorer COM 对象:

    root = "C:\base\dir"
    
    Set ie = CreateObject("InternetExplorer.Application")
    
    For Each f In fso.GetFolder(root).Files
      ie.Navigate "file:///" & f.Path
      While ie.Busy : WScript.Sleep 100 : Wend
    
      text = ie.document.getElementById("MySection").innerText
    
      WScript.Echo Replace(text, vbNewLine, "")
    Next
    

    但是,在 IE 9 之前,&lt;section&gt; 标签不受支持,即使在 IE 9 中,COM 对象似乎也无法正确处理它,因为getElementById("MySection") 只返回开始标签:

    >>> wsh.echo ie.document.getelementbyid("MySection").outerhtml
    <SECTION id=MySection>
    

    不过,您可以使用正则表达式:

    root = "C:\base\dir"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    Set re1 = New RegExp
    re1.Pattern = "<section id=""MySection"">([\s\S]*?)</section>"
    re1.Global  = False
    re2.IgnoreCase = True
    
    Set re2 = New RegExp
    re2.Pattern = "(<br>|\s)+"
    re2.Global  = True
    re2.IgnoreCase = True
    
    For Each f In fso.GetFolder(root).Files
      html = fso.OpenTextFile(filename).ReadAll
    
      Set m = re1.Execute(html)
      If m.Count > 0 Then
        text = Trim(re2.Replace(m.SubMatches(0).Value, " "))
      End If
    
      WScript.Echo text
    Next
    

    【讨论】:

      【解决方案2】:

      这里是使用perl 和来自Mojolicious 框架的HTML 解析器的单线解决方案:

      perl -MMojo::DOM -E '
          say Mojo::DOM->new( do { undef $/; <> } )->at( q|#MySection| )->text
      ' index.html
      

      假设index.html具有以下内容:

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      </head>
      <body id="portada">
      <section id="MySection">
      Some text here
      another line here <br>
      last line of text.
      </section>
      </body>
      </html>
      

      它产生:

      Some text here another line here last line of text.
      

      【讨论】:

      • +1 建议使用适当的解析器和整体优雅的解决方案。
      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      相关资源
      最近更新 更多