LoginSignup
26

More than 5 years have passed since last update.

PythonとRubyで簡単なWebスクレイピング

Posted at

Webスクレイピング -> WebサイトのHTMLデータを収集して、特定のデータを抽出・整形することです。

今回はPythonとRubyのやり方の1つをそれぞれ紹介します。

Python: BeautifulSoup4

PythonではBeautifulSoupを使うとけっこう便利です。

インストール

pip install beautifulsoup4

使い方

import urllib2
from bs4 import BeautifulSoup

html = urllib2.urlopen("http://example.com")
# => もちろんファイルを読み込んだりもできます。

soup = BeautifulSoup(html)

# 便利なメソッドがいっぱい!
soup.find_all('td')
soup.find("head").find("title")
soup.find_parents()
soup.find_parent()
soup.descendants()

# タグの名前変更、属性値の変更、追加、削除も出来るみたいです!
tag = soup.a
tag.string = "New link text."
tag
# => <a href="">New link text.</a>

soup = BeautifulSoup("<a>Foo</a>")
soup.a.append("Bar")
# => <a href="">FooBar</a>

Pythonってほぼつかったことないけどけっこう楽しく使えました。

Ruby: nokogiri

インストール

gem install nokogiri
source 'https://rubygems.org'
gem 'nokogiri'
bundle

使い方

charset = nil
html = open("http://example.com") do |f|
  charset = f.charset 
  f.read 
end

doc = Nokogiri::HTML.parse(html, nil, charset)

doc.title
doc.xpath('//h2 | //h3').each do |link|
  puts link.content
end
html = File.open('data.html', encoding: 'utf-8') { |file| file.read }
doc = Nokogiri::HTML.parse(html, nil) do |d|
  d.xpath('//td').each do |td|
    pp td.content
  end
end

個人的にはやっぱりRubyが好きでした。

参考

PythonとBeautiful Soupでスクレイピング - Qiita
http://qiita.com/itkr/items/513318a9b5b92bd56185
kondou.com - Beautiful Soup 4.2.0 Doc. 日本語訳 (2013-11-19最終更新)
http://kondou.com/BS4/#
Nokogiri を使った Rubyスクレイピング [初心者向けチュートリアル] - 酒と泪とRubyとRailsと
http://morizyun.github.io/blog/ruby-nokogiri-scraping-tutorial/

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
26