スクレイピングについて


2019年の記事です。クラスの話題をしていました。

takkii/Pylean、このレポジトリでPythonを利用したスクレイピングをしています。

※ 今後、レポジトリを更新するかもしれません。まだ未完成です。これからもう少し改良予定です。

緊急事態宣言が解除されてから、東京都や北海道でコロナ感染者が多数確認されコロナ第3波がやってきそうな勢いがあります。コロナウイルスの状況を日本に限定して、スクレイピングをしていきます。誰も他人事にできない状況です。現在をいつもの端末でみることで、コロナ禍に慌てずに新生活様式を意識して生活していきます。苦境に負けるな。(コロナ禍はころなかといいます)

スクレイピング

import re
import threading
from requests_html import HTMLSession
from bs4 import BeautifulSoup

class corona_ja_result(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
      session = HTMLSession()
      response = session.get('https://corona-stats.online/Japan')
      soup = BeautifulSoup(response.text,"lxml")
      [s.decompose() for s in soup('style')]
      pat = re.compile(r"<[^>]*?>")
      corona_ja_result = (pat.sub("", soup.text))
      print(corona_ja_result)

thread = corona_ja_result()
thread.run()

スクレイピング結果

Coronavirus Tracker

╔══════╤════════════╤══════════════╤═════════════╤══════════════╤══════════════╤════════════╤════════════╤══════════╤════════════════╗
║ Rank │ Country    │ Total Cases  │ New Cases ▲ │ Total Deaths │ New Deaths ▲ │ Recovered  │ Active     │ Critical │ Cases / 1M pop ║
╟──────┼────────────┼──────────────┼─────────────┼──────────────┼──────────────┼────────────┼────────────┼──────────┼────────────────╢
║ 1    │ Japan (JP) │      130,179 │             │        1,974 │              │    111,163 │     17,042 │      323 │          1,031 ║
╟──────┼────────────┼──────────────┼─────────────┼──────────────┼──────────────┼────────────┼────────────┼──────────┼────────────────╢
║      │ World      │   59,032,742 │    61,793 ▲ │    1,394,389 │      1,157 ▲ │ 40,306,677 │ 17,331,676 │  103,006 │       7,574.13 ║
╚══════╧════════════╧══════════════╧═════════════╧══════════════╧══════════════╧════════════╧════════════╧══════════╧════════════════╝

Code: https://github.com/sagarkarira/coronavirus-tracker-cli
Twitter: https://twitter.com/ekrysis

Last Updated on: 23-Nov-2020 08:11 UTC

US STATES API: https://corona-stats.online/states/us
HELP: https://corona-stats.online/help
SPONSORED BY: Vercel
Checkout fun new side project I am working on: https://messagink.com

依存ライブラリインストーラ

import importlib
import platform
import site
import subprocess
import sys
import traceback

class InstallerClass:
    sci_win = ['python', '-m', 'pip', 'install', 'scikit-learn']
    nump_win = ['python', '-m', 'pip', 'install', 'numpy']
    pan_win = ['python', '-m', 'pip', 'install', 'pandas']
    req_win = ['python', '-m', 'pip', 'install', 'requests-html']
    bs4_win = ['python', '-m', 'pip', 'install', 'beautifulsoup4']
    mat_win = ['python', '-m', 'pip', 'install', 'matplotlib']

    sci = ['python3', '-m', 'pip', 'install', 'scikit-learn']
    nump = ['python3', '-m', 'pip', 'install', 'numpy']
    pan = ['python3', '-m', 'pip', 'install', 'pandas']
    req = ['python3', '-m', 'pip', 'install', 'requests-html']
    bs4 = ['python3', '-m', 'pip', 'install', 'beautifulsoup4']
    mat = ['python3', '-m', 'pip', 'install', 'matplotlib']

    def sci_win_method(self):
        try:
            ret_sci_win = subprocess.run(self.sci_win, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_sci_win)
        except Exception:
            traceback.print_exc()
    def nump_win_method(self):
        try:
            ret_nump_win = subprocess.run(self.nump_win, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_nump_win)
        except Exception:
            traceback.print_exc()
    def pan_win_method(self):
        try:
            ret_pan_win = subprocess.run(self.pan_win, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_pan_win)
        except Exception:
            traceback.print_exc()
    def req_win_method(self):
        try:
            ret_req_win = subprocess.run(self.req_win, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_req_win)
        except Exception:
            traceback.print_exc()
    def bs4_win_method(self):
        try:
            ret_bs4_win = subprocess.run(self.bs4_win, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_bs4_win)
        except Exception:
            traceback.print_exc()
    def mat_win_method(self):
        try:
            ret_mat_win = subprocess.run(self.mat_win, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_mat_win)
        except Exception:
            traceback.print_exc()


    def sci_method(self):
        try:
            ret_sci = subprocess.run(self.sci, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_sci)
        except Exception:
            traceback.print_exc()
    def nump_method(self):
        try:
            ret_nump = subprocess.run(self.nump, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_nump)
        except Exception:
            traceback.print_exc()
    def pan_method(self):
        try:
            ret_pan = subprocess.run(self.pan, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_pan)
        except Exception:
            traceback.print_exc()
    def req_method(self):
        try:
            ret_req = subprocess.run(self.req, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_req)
        except Exception:
            traceback.print_exc()
    def bs4_method(self):
        try:
            ret_bs4 = subprocess.run(self.bs4, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_bs4)
        except Exception:
            traceback.print_exc()
    def mat_method(self):
        try:
            ret_mat = subprocess.run(self.mat, encoding='utf-8', stderr=subprocess.PIPE)
            print(ret_mat)
        except Exception:
            traceback.print_exc()

if sys.version_info[0] == 2:
  print("This installer is Python2 not supported.")

elif sys.version_info[0] == 3:
    pf = platform.system()
    if pf == 'Windows':
       InstClass = InstallerClass()
       InstClass.sci_win_method()
       InstClass.nump_win_method()
       InstClass.pan_win_method()
       InstClass.req_win_method()
       InstClass.bs4_win_method()
       InstClass.mat_win_method()

    elif pf == 'Darwin':
       InstClass = InstallerClass()
       InstClass.sci_method()
       InstClass.nump_method()
       InstClass.pan_method()
       InstClass.req_method()
       InstClass.bs4_method()
       InstClass.mat_method()

    elif pf == 'Linux':
       InstClass = InstallerClass()
       InstClass.sci_method()
       InstClass.nump_method()
       InstClass.pan_method()
       InstClass.req_method()
       InstClass.bs4_method()
       InstClass.mat_method()

    else:
       print("Installer does not support OS other than Windows, MacOS and Linux kernel.")


else:
  print("A version other than Python2 and Python3. Does not match.")

importlib.reload(site)

requirements.txtにライブラリを記載して、pip3 install -r requirements.txtを実行する手もあります。

それでは、Pythonを知ることにならないので実際にインストーラを作ってました。

拡張性があり、知りたい情報を手に入れるようにカスタマイズできますね。

2020年の話題でした。今年もありがとうございました。来年もよろしくお願いします。

メリークリスマス 🎅アンド🎄 ハッピーニューイヤー🎍