8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonで読書メーターからデータを取得する

Posted at

python3で読書メーターからデータを取得する方法について書いておきます.
いろんな方法があると思いますが,個人的な趣味でpython3とscrapyを使います.

python3でもscrapyを使うために,pipでpython3に対応したバージョンをインストールします.

pip install scrapy==1.1.0rc1

自分が必要だったのは,読み終わった日付と本のタイトル,ページ数だったので,
それを表示するようにしました.

scrapy runspider bookmeter.py > a.csv

ソースコードを以下に貼っておきます.
参考になれば.

bookmeter.py
import scrapy
import datetime
from scrapy.http import Request

class LoginSpider(scrapy.Spider):
    name = 'bookmeter'
    start_urls = ['http://bookmeter.com/login']

    def __init__(self):
        self.list_num = 1
        self.booklist_url = 'http://bookmeter.com/home?main=book&display=list&p='
        self.data = []

        self.mail = 'ここにメールアドレス'
        self.password = 'ここにパスワード'

    def getURL(self):
        return self.booklist_url + str(self.list_num)

    def parse(self, response):
        return scrapy.FormRequest.from_response(
            response,
            formnumber=1,
            formdata={'mail': self.mail, 'password': self.password},
            callback=self.after_login
        )

    def after_login(self, response):
        return Request(url=self.getURL(), callback=self.parse_list)

    def parse_list(self, response):
        maxnum = int(response.xpath("//input[@id='pages']/@value").extract()[0])

        for i in response.xpath("//div[@class='book_list_simple_box']"):
            elems = i.xpath("div/div")
            jd = elems[0].xpath("text()").extract()[0].strip()
            if jd == "読了日":
                continue
            d = datetime.datetime.strptime(elems[0].xpath("text()").extract()[0].strip(), '%Y年%m月%d日')
            t = elems[1].xpath('a/text()').extract()[0]
            p = elems[3].xpath('span/text()').extract()[0]
            self.data.append((d, t, p))

        if self.list_num == maxnum:
            for d, t, p in self.data:
                print("%s, %s, %s" % (d.strftime("%Y-%m-%d"), t, p))
        else:
            self.list_num += 1
            return Request(url=self.getURL(), callback=self.parse_list)
8
10
0

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
8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?