LoginSignup
101
101

More than 5 years have passed since last update.

Nokogiriを使用したクローラーめも

Posted at

文字コードの変更

require 'kconv'

str = "日本語の文字列"

puts str.tosjis => shift_jisに変換
puts str.toutf8 => utf-8に変換

Nokogiri

NodeとNodeSetとElement

NodeとNodeSetの違いについて理解する必要がある。

Nodeset

Nodeを格納したリスト型は配列

Node

NodeSetに格納されているもの
(例)

require 'nokogiri'
require 'open-uri'

html = open("http://XXXXXXX")
doc = Nokogiri::HTML.parse(html, nil, "UTF-8")

nodesets = doc.xpath('//title')
puts nodesets.text
puts nodesets.inner_text
puts nodesets.first_inner_text

nodesets.each do |nodeset|
puts nodeset.text
puts nodeset.inner_text
end

検索系のメソッド

doc.at('//title')  => 検索にヒットした最初のノード

doc.at_xpath('//title')  => xpathの検索にヒットした最初のノード

doc.at_css('title')  => cssの検索にヒットした最初のノード

doc.css('title')  => cssで検索。Nodeset

doc.css('title')[0]  => cssで検索。NodeSetから最初のノード

doc.xpath('//title')  => xpathで検索。最初のNode

doc.xpath('//title')[0]  => xpahtで検索。NodeSetから最初のNode

doc.search('title')
xpathかcssで検索。NodeSet

doc.search('title')[0]  => xpathかcssで検索。NodeSetから最初のNode

Nokogiriの検索・参照系メソッド

at

cssかxpathで検索し、ヒットした最初のElementをとりだす

at_css

cssで検索し、ヒットした最初のElementをとりだす

at_xpath

xpathで検索し、ヒットした最初のElementをとりだす

css

cssで検索し、NodeSetを返す

xpath

xpathで検索し、NodeSetを返す

search

cssかxpathで検索し、NodeSetを返す

content

コンテンツ(タグで囲まれた部分)を返す

inner_html

タグ内のHTMLを返す

inner_text

タグ内のテキスト文を返す

to_html

要素全体を返す

to_s

要素全体を返す

to_str

stringで返す

to_xhtml

要素全体を返す

to_xml

要素全体を返す

便利なやつ

Google

指定した文字を検索させ、検索結果を取得する

require 'google-search'

Google::Search::Web.new(:query => 'クローラー').each do |item|
puts item.url
puts item.title
end

Google Custom Search APIを使用するのあり

Amazon

Product Advertising API

Twitter

Twitter Streaming API

Facebok

Facebook Graph API

101
101
1

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