Created
November 12, 2012 12:15
-
-
Save higaki/4059052 to your computer and use it in GitHub Desktop.
learn ruby@KOF2012 ex1 (Nokogiri)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# -*- coding: utf-8; -*- | |
# Ruby初級者向けレッスン KOF出張版 | |
# 演習問題 1 | |
# Nokogiri を使って <a href="...">...</a> から URL とテキストを抜き出す例 | |
# id="wiki-body" 内のみ処理する。 | |
require 'nokogiri' | |
# 結果は [Nokogiri::XML::Element, Nokogiri::XML::Element ...] となります。 | |
def scrape_css fn | |
Nokogiri::HTML(open(fn)).search("#wiki-body a") | |
end | |
# 文字列は Nokogiri::XML::Element#content で取り出せます。 | |
# URL は Nokogiri::XML::Element#values で取り出せます。 | |
# values は配列を返すので (どうしてでしょうね) その最初の要素を取り出します。 | |
scrape_css("rubykansai.html").each do |elem| | |
puts "#{elem.content}: #{elem.values.first}" | |
end | |
# 間違いがあれば、ご指摘ください。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment