4

テキストを抽出する必要がある HTML ファイルが多数あります。すべてが 1 行にある場合は、非常に簡単に実行できますが、タグが折り返されていたり、複数の行にある場合は、これを行う方法がわかりません。これが私が意味することです:

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

<br>テキストを折り返すのに役立つ場合を除き、テキストについては気にしません。私が望む領域は常に「MySection」で始まり、次に で終わり</section>ます。私が終わらせたいのは次のようなものです:

Some text here  another line here  last line of text.

vbscript やコマンド ライン オプション (sed?) などを使用したいのですが、どこから始めればよいかわかりません。何か助けはありますか?

4

2 に答える 2

4

通常、これには 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

ただし、この<section>タグは IE 9 より前ではサポートされておらず、IE 9 でもgetElementById("MySection")開始タグのみを返すため、COM オブジェクトはそれを正しく処理していないようです。

>>> 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
于 2013-05-18T23:53:55.363 に答える
1

ここでは、フレームワークperlの HTML パーサーを使用したワンライナー ソリューションを示します。Mojolicious

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.
于 2013-05-18T22:16:44.580 に答える