21
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nokogiriの使い方メモ(XPathを使った場合)

Last updated at Posted at 2016-10-02

Nokogiriのサンプルをメモ。

Youtubeで「Ruby on Rails」と検索して、結果の動画のタイトルの一覧を表示する。

nokogiri_sample.rb
require 'open-uri'
require 'nokogiri'

# Youtubeで「ruby on rails」で検索した結果の動画のタイトルの一覧を取得する。

# youtubeでruby on railsを検索
doc = Nokogiri::HTML(open('https://www.youtube.com/results?q=ruby+on+rails&sp=CAI%253D'))

# 動画のノードの一覧を取得
# ドキュメント全体を検索する場合は「//をつける」
nodes = doc.xpath("//div[@class='yt-lockup-dismissable yt-uix-tile']")

nodes.each do |node|
  # このノード以下のすべての子要素に対して検索を行う場合は「.//」をつける
  title_node = node.xpath(".//h3[@class='yt-lockup-title ']")
  # 子要素のみを検索対象とする場合は何もつけない
  title = title_node.xpath("a")
  puts title.text
end
21
26
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
21
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?