Skip to content

Instantly share code, notes, and snippets.

@ytera
Last active September 15, 2015 02:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytera/55ae106764d2dec57c11 to your computer and use it in GitHub Desktop.
Save ytera/55ae106764d2dec57c11 to your computer and use it in GitHub Desktop.
読書メーターに登録されている本の読者数を取得するスクリプト
# -*- encoding: utf-8 -*-
require 'mechanize'
require 'nokogiri'
require 'kconv'
require 'fileutils'
# ハッシュ
module HashInitializable
def initialize(attributes={})
attributes.each do |name,value|
send("#{name}=",value)
end
end
end
class HashInitializableStruct
def self.new(*arguments)
struct = Struct.new(*arguments)
struct.send(:include, HashInitializable)
struct
end
end
properties = [:id,:name,:reader_num]
Book = HashInitializableStruct.new(*properties)
books = Hash.new
# メイン
agent = Mechanize.new
agent.user_agent = 'Mac Safari'
f_in = open(ARGV[0], "r")
for a in f_in
book_url = 'http://bookmeter.com/b/' + a
page = agent.get(book_url)
doc = Nokogiri::HTML(page.content.toutf8)
node = doc.xpath("//*[@id=\"side_left\"]/div/div/div/div/div/span").first
reader_num = node.text
name = doc.title
puts name.split("感想")[0]+reader_num
book_property = {id: a, name: name.split("感想")[0], reader_num: reader_num.split("登録")[0]}
book = Book.new(book_property)
books.store(book.id,book)
books
end
# ファイル出力
day = Time.now
out_name = day.strftime("%m%d%H%M") + ".csv"
f_out = open(out_name, "w")
f_out.printf("%s,%s/%s,%s:%s:%s,",day.year,day.month,day.day,day.hour,day.min,day.sec)
books.each_value do |book|
f_out.printf("%s,",book.reader_num.split("登録")[0])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment