pythonでWebスクレイピング

Blog Single

みなさん、こんにちは。

最近ハンドスピナーにハマってます、渋谷です。

以前、Go言語で簡単なWebスクレイピングという記事が投稿されておりましたが、今回はpythonでWebスクレイピングをしようと思います。

環境

$ python3 --version
Python 3.7.0

$ pip3 --version
pip 18.0

ライブラリのインストール

Requests

Webページを取得するためのHTTPライブラリ。

$ pip3 install requests

Beautiful Soup

Requestsで取得したWebページからスクレイピングするためのライブラリ。

$ pip3 install beautifulsoup4

コーディング

それでは、実際にコーディングしていきます。
今回はMediumというサイトから、前日投稿された記事を閲覧数順に並べ替えたものの中から拍手(いいねのようなもの)が900以上付いていることを条件に、10件取得してきます。

# scraping.py

from datetime import datetime, date, timedelta
import sys
import re
import requests
from bs4 import BeautifulSoup

# 昨日の日付を取得する
# 例)2018/08/01
today = datetime.today()
yesterday_calc = today - timedelta(days=1)
yesterday = datetime.strftime(yesterday_calc, '%Y/%m/%d')

# 引数からタグを取得
if len(sys.argv) != 2:
    print("タグを指定してください")
    sys.exit()
else:
    tag_name = sys.argv[1]

# MediumのURLを作成
url = "https://medium.com/tag/" + tag_name + "/archive/" + yesterday

html = requests.get(url)

soup = BeautifulSoup(html.content, "html.parser")

# 記事を取得
article_element = soup.find_all("div", class_="streamItem streamItem--postPreview js-streamItem")

# 10件だけ取得
count = 0
for i in article_element:
    # 記事のタイトル取得
    article_title_tag = i.find("h3", class_="graf--title")
    if article_title_tag:
        article_title = article_title_tag.getText()
    else:
        article_title = '';

    # 記事へのリンクを取得
    article_url_tag = i.find(class_="link link--darken")
    article_url = article_url_tag.get("href")

    # clap数
    clap_count_tag = i.find("button", class_="button button--chromeless u-baseColor--buttonNormal js-multirecommendCountButton u-disablePointerEvents")
    if clap_count_tag:  
        clap_count = clap_count_tag.getText()
    else:
        clap_count = "0";

    if re.findall('K' , clap_count) or int(clap_count) >= 900:
        print("タイトル : " + article_title)
        print("URL : " + article_url)
        print("拍手数 : " + clap_count + '\n')
        count = count + 1

    if count == 10:
        sys.exit()

実行

下記コマンドで実行しましょう。
今回は引数にタグを指定出来るようにしました。

$ python3 scraping.py blockchain

10件の記事のタイトル・URL・拍手数が以下のように表示されているはずです。

タイトル : Them Lightning Network Nodes Sure Do Look Centralized To Me! What Gives?
URL : https://medium.com/@StopAndDecrypt/them-lightning-network-nodes-sure-do-look-centralized-to-me-what-gives-ee39c9b12ac0?source=tag_archive---------0---------------------
拍手数 : 1.7K

タイトル : Introducing Demux — Deterministic Databases Off-Chain Verified by the EOSIO Blockchain
URL : https://medium.com/eosio/introducing-demux-deterministic-databases-off-chain-verified-by-the-eosio-blockchain-bd860c49b017?source=tag_archive---------3---------------------
拍手数 : 1.5K

タイトル : Airdrop of CryptoGladiator in the NNS community
URL : https://medium.com/neweconolab/airdrop-of-cryptogladiator-in-the-nns-community-15c07334e441?source=tag_archive---------5---------------------
拍手数 : 934

タイトル : OST Project Roadmap 2017–2021: Scaling Blockchain Economies to Billions of Users
URL : https://medium.com/ostdotcom/ost-project-roadmap-2017-2021-scaling-blockchain-economies-to-billions-of-users-7754f58112a6?source=tag_archive---------6---------------------
拍手数 : 1.6K

タイトル : NKN’s statement on Binance voting decision
URL : https://medium.com/nknetwork/nkns-statement-on-binance-voting-decision-d1ab161ca770?source=tag_archive---------7---------------------
拍手数 : 1.2K

タイトル : We’re Not Doing a Big ICO
URL : https://medium.com/elrondnetwork/were-not-doing-a-big-ico-6fdc9ce62a44?source=tag_archive---------8---------------------
拍手数 : 1.3K

タイトル : Blockchain Cuties — 1.24 patch notes
URL : https://medium.com/@blockchaincutie/blockchain-cuties-1-24-patch-notes-402c53a49fac?source=tag_archive---------43---------------------
拍手数 : 1.6K

タイトル : ? Weekly Progress Update — 23 to 29 July 2018
URL : https://medium.com/sentinelchain/weekly-progress-update-23-to-29-july-2018-208749b16564?source=tag_archive---------76---------------------
拍手数 : 1K

タイトル : OmiseGo Gold Airdrop: How to Get free 100,000 OMGG Tokens
URL : https://medium.com/@Omisego_Gold/omisego-gold-airdrop-how-to-get-free-100-000-omgg-tokens-fcaa647ce54?source=tag_archive---------178---------------------
拍手数 : 1.92K

まとめ

今回はスクレイピング結果をターミナル上に表示するだけでしたが、今後はこれを応用して何かしようと考えているところです。
ただし、スクレイピングはサーバーに過度な負荷を与える可能性があるので、その点に注意しながらプログラムを作成しましょう。
私はまだpythonを触り始めたばかりですが、興味のある方は是非触ってみてください。

Posted by ShibuyaYuuki
今はPHPで開発を行なっているエンジニア。 就職してから体重が15キロ増えました!!

Other Posts: