LoginSignup
1
1

More than 3 years have passed since last update.

Ruby, Nokogiri : セレクトしているノードの要素名を取得する

Last updated at Posted at 2020-05-23

はじめに

Nokogiriでは、cssまたはat_cssで要素の名前を指定することでノードをセレクトできますが、逆にセレクトしているノードから要素名はどのように取得するのか気になったので、調べてみました。

nameメソッドを使う

ノードの要素名取得はとてもシンプルです。以下のようなhtmlファイルがあったとします。

hello.html
<html>
  <head>
    <title>hello</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <p>こんにちは</p>
  </body>
</html>

at_cssでpタグを選択します。

sample.rb
require 'nokogiri'

html = open('hello_utf8.html').read
doc = Nokogiri::HTML.parse(html)

element = doc.at_css('p')

p element.name  #=> 'p'
p element.parent.name  #=> 'body'

parentなどを使って他のノードをセレクトし、要素名を取得することもできます。

さいごに

普通はhtml構造を先に見てからスクレイピングするので、ノードから要素名を取得する需要はあまりないと思います^^;

1
1
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
1