TEDの英語原稿を取得する

移転しました。

方針

http://www.ted.com/talks/subtitles/id/#{固有のID}/lang/en を叩くと、英語原稿のjsonが返ってくる。
TEDのビデオの固有のIDを取得して、API叩いて、jsonをparseして、出力すればいけそう。

jsonのパース
gem install json
require 'rubygems'
require 'open-uri'
require 'json'

open("http://www.ted.com/talks/subtitles/id/1183/lang/en") do |f|
  json = JSON.parse(f.read)
  json['captions'].each do |j|
    puts j['content']
  end
end


こんな感じで取得できそう。


固有IDを取得するために、nokogiriでHTMLをparseする

Nokogiri
Installationを参照して nokorigiのgemを入れる


brew update
brew install libxml2 libxslt
gem install nokogiri
require 'rubygems'
require 'open-uri'
require 'json'
require 'nokogiri'

url = "http://www.ted.com/talks/brene_brown_listening_to_shame.html"
doc = Nokogiri::HTML(open(url))

ted_id = doc.xpath("//div[@id='share_and_save']").first.attribute("data-id")

open("http://www.ted.com/talks/subtitles/id/#{ted_id}/lang/en") do |f|
  json = JSON.parse(f.read)
  json['captions'].each do |j|
    puts j['content']
  end
end


スクレイピングの方法がわからなくて四苦八苦。以下を参照して、怪しげながら、固有IDの取得。
document/ruby nokogiri スクレイピング - weiki (作業ログやそのまとめ)
XPath入門、実用例 - 素人がプログラミングを勉強するブログ


できた

TED