東洋経済オンライン「新型コロナウイルス国内感染の状況」用の厚生労働省データソースをスクレイピングで作成

※現在は厚生労働省フォーマットが変更されているため対応していません

都道府県の新型コロナまとめサイトのdata.jsonの作り方

imabari.hateblo.jp

imabari.hateblo.jp

ソース

toyokeizai.net

github.com

手順

  1. Githubの全データをウェブサイトにアップ
  2. 「data/data.json」を下で作成されたdata.jsonで上書き
  3. index.htmlの最新更新日は自分で更新
  4. index.htmlにアクセス

完成

imabari.jpn.org

最新の患者情報

こちらの情報から追記 imabari.hateblo.jp

スクレイピング

pip install beautifulsoup4
pip install pandas
pip install requests
pip install jaconv
import re
from urllib.parse import urljoin

import jaconv
import pandas as pd
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
}


def get_link():

    url = "https://www.mhlw.go.jp/stf/seisakunitsuite/bunya/0000121431_00086.html"

    r = requests.get(url, headers=headers)

    r.raise_for_status()

    soup = BeautifulSoup(r.content, "html5lib")

    href = (
        soup.find("div", class_="l-contentMain")
        .find(string=re.compile(r"^新型コロナウイルス感染症の現在の状況と厚生労働省の対応について"))
        .find_parent("a")
    )

    link = urljoin(url, href.get("href"))

    return link


def zen2han(x):

    x = jaconv.z2h(x, digit=True)

    return x


url = get_link()

# URL表示
print(url)

r = requests.get(url, headers=headers)

r.raise_for_status()

soup = BeautifulSoup(r.content, "html5lib")

# タイトル表示
print(soup.find("h1").get_text(strip=True))


dfs = pd.read_html(soup.prettify(), header=0)


df1 = dfs[2].copy()

df1.rename(columns={"濃厚接触者  の状況": "濃厚接触者の状況"}, inplace=True)

df1["居住地"] = df1["居住地"].str.replace(r"\s+", "")

df1["周囲の患者の発生※"] = (
    df1["周囲の患者の発生※"].replace(r"(?<=\d)\s+", "、", regex=True).str.replace(r"\s+", "")
)

df1["濃厚接触者の状況"] = df1["濃厚接触者の状況"].str.replace(r"特定\s", "特定、").str.replace(r"\s+", "")

df1["新No."] = df1["新No."].apply(zen2han)

df1["旧No."] = df1["旧No."].apply(zen2han)

df1

df1.to_csv("data.csv", index=False)

df1.insert(0, "空", "")

df1.to_json("data.json", orient="values", force_ascii=False)