Skip to content

Instantly share code, notes, and snippets.

@baboocon baboocon/kyodoku.rb
Created Apr 25, 2015

Embed
What would you like to do?
読書メーターにログイン状態でアクセスし、お気に入りユーザーの読書状況を一括取得するRubyスクリプト
# -*- coding: utf-8 -*-
require 'mechanize'
require 'nokogiri'
require 'kconv'
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,:user_url,:kyodoku_cnt,:yonda_cnt,:yonderu_cnt,:tsundoku_cnt,:yomitai_cnt]
User = HashInitializableStruct.new(*properties)
users = Hash.new
agent = Mechanize.new
agent.user_agent = 'Mac Safari'
base_url = 'http://bookmeter.com'
login_url = base_url + '/login'
my_url = base_url + '/u/YOUR_ID' # YOUR_IDには自分のIDを入れる
favorite_url = my_url + '/favorite_user'
agent.get(login_url) do |page|
page.form_with(:action => '/login') do |form|
formdata = {
:mail => 'EMAIL_ADDRESS', # 自分のログイン用メールアドレスを入れる
:password => 'PASSWORD', # 自分のパスワードを入れる
}
form.field_with(:name => 'mail').value = formdata[:mail]
form.field_with(:name => 'password').value = formdata[:password]
end.submit
end
html = agent.get(favorite_url).content.toutf8
if html =~ %r!<center>1/(\d+)<br />.+</center>!
page_max = $1.to_i
end
(1..page_max).each do |i|
each_favorite_url = favorite_url + "&p=" + i.to_s
page = agent.get(each_favorite_url)
doc = Nokogiri::HTML(page.content.toutf8)
doc.xpath("//*[@id=\"main_left\"]/div/div/a").each do |node|
id = node['href'].to_s.gsub(/\/u\//, '').to_i
name = node.text
url = base_url + node['href'].to_s
user_property = {id: id, name: name, user_url: url, kyodoku_cnt: 0, yonda_cnt: 0, yonderu_cnt: 0, tsundoku_cnt: 0, yomitai_cnt: 0}
user_content = Nokogiri::HTML(agent.get(user_property[:user_url]).content.toutf8)
doc = user_content.xpath("//*[@id=\"main_right\"]/div/h3")
doc.each do |node|
case node.text.strip
when /共読本\((\d+)\)/
user_property[:kyodoku_cnt] = $1.to_i
when /読み終わった本\((\d+)\)/
user_property[:yonda_cnt] = $1.to_i
when /読んでる本\((\d+)\)/
user_property[:yonderu_cnt] = $1.to_i
when /積読本\((\d+)\)/
user_property[:tsundoku_cnt] = $1.to_i
when /読みたい本\((\d+)\)/
user_property[:yomitai_cnt] = $1.to_i
else
next
end
user_property
end
user = User.new(user_property)
users.store(user.id,user)
users
end
end
users.each_value do |user|
puts "ID: #{user.id}, 名前: #{user.name}, 共読本: #{user.kyodoku_cnt}冊, 読み終わった本: #{user.yonda_cnt}冊, 読んでる本: #{user.yonderu_cnt}冊, 積読本: #{user.tsundoku_cnt}冊, 読みたい本: #{user.yomitai_cnt}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.