16
18

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(Ruby)の使い方 - Rubyでクローラーを作る -

Posted at

Nokogiri

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

URL = ARGV[0]
doc = Nokogiri::HTML(open(URL))

p doc

実行する

$ ruby anemone.rb http://www.example.com/

注) http://www.example.com/ には任意のURLを入力してください。
  サイトによってはクローリングに時間がかかるのでご注意ください。


メソッド

メソッド 概要
title titleを取得(文字列)
at_css CSS検索(セレクター)で最初に一致した要素を取得
css CSS検索(セレクター)で一致した要素を全て、ノードで取得
inner_html 指定した要素(タグ)内のHTMLを返す。
content, inner_text, text, to_str 指定した要素(タグ)内の文字を返す。(タグは除外)
to_s, to_html 要素全体を返す。

メソッドの使用例

sample02.rb
# -*- coding: utf-8 -*-
require 'nokogiri'
require 'open-uri'

URL = ARGV[0]
doc = Nokogiri::HTML(open(URL))

# title表示
puts doc.title

# ul(tag) を取得(最初に一致したulのブロック)
ul = doc.at_css('ul')

# html表示(ulタグ含む)
puts ul.to_html


# html表示(ulタグ除く)
puts ul.inner_html


# htmlを除外したテキスト表示
puts ul.text


参考サイト

16
18
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
16
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?