Lua:
HTMLの解析
方法:
LuaにはHTMLを解析するための組み込みライブラリはありませんが、LuaHTMLのようなサードパーティのライブラリを利用するか、LuaXMLを通してlibxml2のバインディングを利用することができます。一般的なアプローチは、lua-gumboライブラリを使用してHTMLを解析することであり、これは、直感的で、HTML5に準拠した解析機能を提供します。
lua-gumboのインストール:
まず、lua-gumboがインストールされていることを確認します。通常、luarocksを使用してインストールできます:
luarocks install lua-gumbolua-gumboを使った基本的な解析:
ここでは、lua-gumboを使用してシンプルなHTMLスニペットを解析し、そこからデータを抽出する方法を示します:
local gumbo = require "gumbo"
local document = gumbo.parse[[<html><body><p>Hello, world!</p></body></html>]]
local p = document:getElementsByTagName("p")[1]
print(p.textContent) -- 出力: Hello, world!高度な例 - リンクの抽出:
HTML文書内のすべてのアンカータグ(<a>要素)からhref属性を抽出するには:
local gumbo = require "gumbo"
local document = gumbo.parse([[
<html>
<head><title>サンプルページ</title></head>
<body>
<a href="http://example.com/1">リンク 1</a>
<a href="http://example.com/2">リンク 2</a>
<a href="http://example.com/3">リンク 3</a>
</body>
</html>
]])
for _, element in ipairs(document.links) do
if element.getAttribute then -- エレメントであり、属性を持っていることを確認
local href = element:getAttribute("href")
if href then print(href) end
end
end
-- サンプル出力:
-- http://example.com/1
-- http://example.com/2
-- http://example.com/3このコードスニペットは、ドキュメント内のすべてのリンクを反復処理し、それらのhref属性を印刷します。lua-gumboライブラリのHTML文書の構造を解析し、理解する能力により、タグや属性に基づいて特定の要素を抽出するプロセスが簡素化されます。