スナックelve 本店

バツイチ40代女の日記です

No.2504 はてなダイアリの記事の数を数える

追記

elve.hatenadiary.jp
にもっとスッキリしたコードがあります
====追記終了====

URLは適時変えてくれ


わしのダイアリは1432記事だったようじゃよ。
突っ込みあればよろしくじゃよ。

はてダ 1432
ダメシ 1016
ここ 56*1
合計 2504

たまにチェックしないと危ないなw

追記

No.2504 はてなダイアリの記事の数を数える - スナックelve 本店

lxmlとrequests(意味分からないけど)追加で入れ、どうにかコード実行できました。スクレイピングなかなか面白そう。pythonはおろかまともなプログラミング言語を触ったことがない私ができるのかは疑問だけど…。

2018/03/21 22:03

lxmlとrequests(意味分からないけど)追加で入れ、どうにかコード実行できました。スクレイピングなかなか面白そう。pythonはおろかまともなプログラミング言語を触ったことがない私ができるのかは疑問だけど…。 - bg4kids のブックマーク / はてなブックマーク
おぉ、そうだった。書き忘れていた。ありがとうございます。
Beautifulsoupのほかに

pip install requests
pip install lxml

を実行してインストールしてください。

Visual Studio Code ではターミナルってタブクリックして入力するとインストールされました。
f:id:elve:20180322210038p:plain

ソース

# coding: UTF-8
import requests
from bs4 import BeautifulSoup

# アクセスするURL
url = "http://d.hatena.ne.jp/elve/archive"

# URLにアクセスする htmlが帰ってくる(タグ付き)
html = requests.get(url)         #requestsを使って、webから取得
# htmlをBeautifulSoupで扱う
soup = BeautifulSoup(html.text,'lxml')
cnt = 0
while True:
    #<div class="day">の
    #<li class="archive archive-section">を
    #数える
    lsSectionsDiv = soup.find('div',class_="day")
    lsSections = lsSectionsDiv.find_all('li',class_="archive archive-section")
    #要素数
    cnt = cnt + len(lsSections)
    #次のページを取得
    pageDiv = soup.find('div', class_="calendar", id="pager-top")
    page = pageDiv.find('a', class_="prev")
    if(page==""):
        #ここはこないはず
        break
    else:
        #requestsを使って、webから取得
        try:
            url = page['href']
            html = requests.get(url)         
            # htmlをBeautifulSoupで扱う
            soup = BeautifulSoup(html.text,'lxml')
        except:
            #次のページがないとき=最後のページ
            #ループを抜ける
            break
        pass
print(cnt)

*1:含むこの記事