11
9

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でスクレイピング はてぶ検索

Last updated at Posted at 2017-11-23

こちらの記事をリスペクトして
はてなブックマークからPython人気記事をスクレイピングしてみました。
https://review-of-my-life.blogspot.jp/2017/10/python-web-scraping-data-collection-analysis.html

環境

Ubuntu + python 3.6.3

改修ポイント

掲載のあるコードでは自分の環境で幾つかエラーとなったので対応したり、ほしい情報を付け加えたりとちょっとだけ改修しています。

  • 出力結果の加工はPandasのSeriesとDataFrameを使いました。
     Series -> DataFrameへappendです(定番)。
  • BeautifulSoapを使用しました。
  • ループ判定処理でpager-nextの判定にはlenではなくオブジェクト取得可否に変換しました。オブジェクト取得できないものに対してlenではエラーとなってしまったので。
  • リンクも欲しかったので一緒に収集しました。
  • 次ページリンクの組み立てをしなおしました。
# -*- coding:utf-8 -*-

import pandas as pd
import time
from selenium import webdriver
from bs4 import BeautifulSoup

# はてなブックマークに接続
URL="http://b.hatena.ne.jp/search/text?safe=on&q=Python&users=100"
URL_HEAD=URL.split('?')[0]

# Page Access
driver = webdriver.PhantomJS()
driver.get(URL)
data = driver.page_source.encode('utf-8')
soup = BeautifulSoup(data,'lxml')

# データ蓄積先設定
outputData = pd.DataFrame(index=[],
                          columns=['title', 'bookmarks', 'created', 'link'])
# ページカウント数
page = 1

# 探索ループ
while True:
    if not soup.find(class_='pager-next') is None:
        # Page内探索
        posts = soup.find_all(class_='search-result')

        # 探索対象内ループ検索
        for post in posts:

            # 抽出データ明細作成
            title = post.find('h3').find('a').text
            bookmarks = post.find(class_='users').find('span').text
            created = post.find(class_='entryinfo').find(class_='created').text
            link = post.find(class_='entryinfo').find('a')['href']
            series = pd.Series([title, bookmarks, created, link], index=outputData.columns)

            # データ蓄積
            outputData = outputData.append(series, ignore_index=True)
            print('title: {}'.format(title))

        # ページを一通り探索した後に次のページに遷移する。
        clickNextPageBtn = URL_HEAD + soup.find(class_='pager-next')['href']
        driver.get(clickNextPageBtn)
        page += 1
        driver.implicitly_wait(5)
        
        # 次ページの情報を取得
        data = driver.page_source.encode('utf-8')
        soup = BeautifulSoup(data, 'lxml')

        print("--- Moving to next page ---")
        print('page={}'.format(page))
        time.sleep(5)

    else:
        print("no page any more")
        break

# ファイル出力
outputData.to_csv('/home/xxxxxxxxx/hatena.csv')

# 終了処理(お掃除)
driver.quit()

出力はこんな感じに。


,title,bookmarks,created,link
0,【Python】スクレイピング→データ収集→整形→分析までの流れを初心者...,820, 2017/11/12 ,/entrylist?url=https%3A%2F%2Fqiita.com%2Fm%2
1,なぜ私達は Python から Go に移行したのか - Frasco,360, 2017/10/25 ,/entrylist?url=https%3A%2F%2Ffrasco.io%2F
2,"PHP, Python, Golang を NGINX Unit で動かしてみた - /var/log/study",283, 2017/09/08 ,http://yaaamaaaguuu.hatenablog.com/entry/2017/09/08/031316
3,Python の依存パッケージ管理/環境切り分けツール pipenv の紹介 - 私が...,239, 2017/09/05 ,http://utgwkk.hateblo.jp/entry/2017/09/05/110209
4,pythonで小さなツールを作る時のtips - Qiita,944, 2017/09/04 ,https://qiita.com/m_mizutani/items/c48f67f871d1d41ff4b9
5,Pythonの環境構築を自分なりに整理してみる – Aki Ariga – Medium,459, 2017/08/26 ,https://medium.com/@chezou/dc8d8f2fe989e9
6,Haskellらしさって?「型」と「関数」の基本を解説!【第二言語としての...,230, 2017/08/25 ,https://employment.en-japan.com/engineerhub/entry/2017/08/25/110000
7,スクレイピング初心者がpythonでかわいい猫ちゃん画像をコマンド一発で...,325, 2017/08/23 ,http://karaage.hatenadiary.jp/entry/2017/08/23/073000
8,Pythonでシューティングゲームを作る1(tkinterチュートリアル) : ネット...,167, 2017/08/18 ,http://blog.livedoor.jp/aiko_tech/archives/python_tkinter_gui_game1.html
9,Pythonメモ : あまり知られていない(かもしれない)テクニック その1 -...,107, 2017/08/17 ,http://wonderwall.hatenablog.com/entry/2017/08/17/213431
10,pythonによる画像処理入門 - さもしのブログ,296, 2017/08/16 ,http://www.uosansatox.biz/entry/2017/08/16/002041
11,PythonでCSVを高速&省メモリに読みたい - tkm2261's blog,425, 2017/08/03 ,http://yutori-datascience.hatenablog.com/entry/2017/08/03/230047
12,データサイエンティスト・データエンジニアのための Python ライブラリ...,108, 2017/08/01 ,https://qiita.com/kohei_kimura/items/321322fec2ee8a56889e
13,Pythonメモ : better-exceptionsで例外情報を見やすくする - もた日記,151, 2017/07/24 ,http://wonderwall.hatenablog.com/entry/2017/07/24/162040
14,KING JIM ポメラDM200でEmacs、Vim、Ruby、Pythonが動くなんて素敵すぎ...,877, 2017/07/15 ,http://hitoriblog.com/?p=51448
15,なぜCLIツールはGoで書くべきなのか? Go beyond Python // Speaker Deck,210, 2017/07/15 ,https://speakerdeck.com/doloopwhile/nazeclituruhagodeshu-kubekinafalseka-go-beyond-python

11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?