1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ruby: HTMLパーサGammoでルート以外の要素を起点にcssメソッドを使いたい

Last updated at Posted at 2025-02-17

Gammo は pure Ruby な HTML パーサです。

参考: WHATWG Living StandardとHTMLパーサ - Qiita

本記事は、WHATWG Living Standardに準拠することを目的としたHTMLパーサである「gammo」の紹介を目的としている。


タイトルの通りです。以下の方法でできました、というメモです。

require "gammo"

def my_css(node, expr)
  # ほぼ Gammo::CSSSelector#query_selector_all の実装を流用しただけ
  Gammo::CSSSelector::Traverser.new(expr)
    .evaluate(Gammo::CSSSelector::Context.new(node: node))
end

html = <<~HTML
  <!DOCTYPE html>
  <html>
    <body>
      <div id="div1">
        <span>span 1</span>
      </div>
      <div id="div2">
        <span>span 2</span>
      </div>
    </body>
  </html>
HTML

doc = Gammo.new(html).parse

div2 = doc.css("#div2")[0]
p div2.class #=> Gammo::Node::Element

spans = my_css(div2, "span")
p spans.size #=> 1
p spans[0].inner_text #=> "span 2"

Gammo::Node::Element をオープンクラスして include Gammo::CSSSelector を追加する方法でも動きますが、モンキーパッチを避ける意味では上記の方法が無難かなと思いました。

バージョン

ruby 3.4.1
gammo 0.3.0

この記事を読んだ人は(ひょっとしたら)こちらも読んでいます

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?