群馬県でPythonを使ったAIやシステムを開発しているファントム

Navigation
群馬県でPythonを使ったAIやシステムを開発しているファントム

群馬県でPythonを使ったAIやシステムを開発しているファントムです。企業の経営課題を最適なテクノロジーで解決します。テックブログではPythonを中心にプログラミングに役立つ情報を発信しています。

投稿を検索する


  • 株式会社ファントム コーポレートサイト

カテゴリー



  • AWS 16
  • Django 45
  • FastAPI 4
  • Flask 8
  • GCP 1
  • Information 37
  • Other 32
  • PHP 2
  • Python 93
  • Pythonista 3
  • Rust 1

タグ


Alembic API argparse Beautiful Soup black Channels charset CodeCommit datetime Django REST framework Docker enumerate f-string git GitHub glob Google Colaboratory i18n IAM Internship Jupyter Lambda Matplotlib Nginx OpenCV pandas PIL Pillow PostgreSQL PyCharm PyCon pyenv PyTorch Redis Rembg ReportLab requests S3 Sentry slack tqdm uWSGI venv Vue.js youtube
このサイトはreCAPTCHAによって保護されており、Googleのプライバシーポリシーと利用規約が適用されます。

© 2022 Fantom, Inc.

Hydra WordPress Theme by EckoThemes.

Published with WordPress.

Related Articles

Filter by Category

  • Python(93)
  • Django(45)
  • Information(37)
  • Other(32)
  • AWS(16)
  • Flask(8)
  • FastAPI(4)
  • Pythonista(3)
  • PHP(2)
  • GCP(1)
  • Rust(1)

Filter by Author

  • EIGHT (14)
  • hayai017 (2)
  • press (196)
Back to Latest Articles
Python

気象庁の天気予報をBeautifulSoup4でスクレイピング

気象庁の天気予報をBeautifulSoup4でスクレイピングします。サンプルとして群馬県の週間天気予報(場所、日付、曜日、最高気温、最低気温)を取得します。 コードはGitHubリポジトリにあげています。 週間天気予報 […]

Posted on 10th 7月 2019 by press

Django

DjangoでSQLログを出力して確認する

DjangoでSQLログを出力して確認する方法です。SQLログをリアルタイムで出力して、どういうクエリがどのタイミングで実行されているのか確認できます。設定方法は簡単で、DEBUG = Trueになっている状態でsett […]

Posted on 6th 7月 2019 by press

Django

DockerのPostgreSQLコンテナのリストア

Dockerで動いているPostgreSQLにデータをリストアする方法です。書き出したPostgreSQLのdumpファイル(リストア用データ)はデスクトップに置いてあるという前提で進めます。 ディレクトリ構造 Dock […]

Posted on 4th 7月 2019 by press

Django

Djangoで502 Bad Gatewayが頻発した時に調べたこと

Djangoで開発中のWebアプリで特定のURLにアクセスした時だけ、502 Bad Gatewayが頻発する様になりました。NginxとuWSGIのログを見たらuWSGIのworkerが死んで復活してを繰り返しているこ […]

Posted on 2nd 7月 2019 by press

Django

Djangoでcould not connect to serverエラーが出たら

DjangoでデータベースにPostgreSQLを使ってる際に以下のエラーが出た時の対処方法です。 サーバーのPostgreSQLのディレクトリに移動します。VERSIONの部分はインストールされているバージョンを入力し […]

Posted on 28th 6月 2019 by press

Django

DjangoとChannelsで簡単なチャットサーバーを構築(3)

前回からの続きです。 チャンネルレイヤーを有効化 チャンネルレイヤーを使用するためにバックエンドにRedisを使用します。Redisを使用するためにDockerを起動します。 以下のコマンドを実行してRedisを起動しま […]

Posted on 26th 6月 2019 by press

Django

DjangoとChannelsで簡単なチャットサーバーを構築(2)

前回からの続きです。 ルームビューを作成 chat > templates > chat > room.htmlを作成します。 ルームビューを表示するためのviewを作成します。 ルームビューへのurl […]

Posted on 25th 6月 2019 by press

Django

DjangoとChannelsで簡単なチャットサーバーを構築(1)

こちらのチュートリアルと同じ内容です。https://channels.readthedocs.io/en/latest/tutorial/index.html 環境 Python 3.7.0Django 2.2.2ch […]

Posted on 22nd 6月 2019 by press

Python

Beautiful Soupでoptionタグのvalueを取得する

Beautiful Soupで以下のようなHTMLのoptionタグのvalueを取得する方法です。 optionタグのvalueの値を取得する方法 soup = soup.find_all('option')optio […]

Posted on 15th 6月 2019 by press

Django

Dockerを使ってDjangoとPostgreSQL環境を構築する方法

Dockerを使ってシンプルなDjangoとPostgreSQLの開発環境を構築する方法です。GitHubリポジトリをクローンして以下のコマンドを入力します。 1. Dockerイメージを作成 2. Djangoプロジェ […]

Posted on 8th 6月 2019 by press

Django

DjangoでダウンロードするCSVの文字コードを設定

以下のような、attachmentをつけて即ダウンロードが始まるシステムで、文字コードをShift-JISにする為にto_csv()の引数にencodingをShift-JISに設定しても、ダウンロードするとUTF-8で […]

Posted on 6th 6月 2019 by press

Django

That port is already in use.が表示された時の対処法

Djangoでrunserverコマンドを使って開発用サーバーを起動した時にError: That port is already in use.が表示された時の対処法です。 Error: That port is al […]

Posted on 22nd 5月 2019 by press

Python

Pillowを使って画像を合成する

Pillowを使って画像を合成する方法です。GitHubリポジトリ 上の2つの画像を合成して、下の画像を生成します。 Pillowのインストール バージョン確認 ディレクトリ構造 画像をリサイズ base_image = […]

Posted on 22nd 5月 2019 by press

Python

Pillowを使って画像をリサイズする

Pillowを使って画像をリサイズする方法です。GitHubリポジトリ Pillowのインストール バージョン確認 ディレクトリ構造 画像をリサイズ files = glob.glob('./images/*')imag […]

Posted on 22nd 5月 2019 by press

Python

Pillowを使って画像をクロッピングする

Pillowを使って画像をクロッピングする方法です。ソースコードはGitHubにあげています。 Pillowのインストール バージョン確認 ディレクトリ構造 画像をクロッピング files = glob.glob('./ […]

Posted on 21st 5月 2019 by press

Django

Djangoで開発をする際に仮想環境を構築する方法

Djangoで開発をする際にvenvを使って仮想環境を構築する方法です。pyenvがインストールされていてバージョンを切り替えできる状態を前提に進めます。 仮想環境について Pythonで開発していると開発環境では最新の […]

Posted on 20th 5月 2019 by press

Python

PythonistaでiPhoneから株価をスクレイピング

Pythonistaには多くのモジュールがプリインストールされていて、スクレイピングに必要なBeautifulSoupも初めから使える様になっています。そこで、今回はiOSアプリのPythonistaを使ってiPhone […]

Posted on 2nd 5月 2019 by press

Django

pandasで読み込んだCSVの値がNaNだったときの対処方法

DjangoのWEBプリケーションでCSVをpandasで読み込んでforで一行ずつループ処理をしたところ、毎回決まったところで決まったエラーが出たのでPyCharmのデバッグ機能を使って原因を調べた内容です。 プログラ […]

Posted on 28th 4月 2019 by press

Python

Pythonでフォルダ内のファイルを別のフォルダにコピー

Pythonであるフォルダ内のファイルを別のフォルダにコピーする方法です。 ディレクトリ構造(ファイルのコピー後) directory = (os.getcwd())現在のディレクトリを取得します。 image_path […]

Posted on 28th 4月 2019 by press

Python

Pythonでディレクトリ内のファイルを取得する

globモジュールを使いディレクトリ内にあるファイルを取得する方法です。 ディレクトリ構造 まずはディレクトリ内のjpgを全て取得します。 directory = (os.getcwd())で現在のディレクトリのパスを取 […]

Posted on 26th 4月 2019 by press

View Latest Posts
Python

気象庁の天気予報をBeautifulSoup4でスクレイピング


press
気象庁の天気予報をBeautifulSoup4でスクレイピング
Posted on 10th 7月 2019 by press
2024年度 インターンシップ 募集開始

気象庁の天気予報をBeautifulSoup4でスクレイピングします。サンプルとして群馬県の週間天気予報(場所、日付、曜日、最高気温、最低気温)を取得します。

コードはGitHubリポジトリにあげています。

週間天気予報のスクレイピング

各要素を取得

週間天気予報の情報以下のテーブル内にあります。

取得するテーブルのソース

日付と曜日は、1個目の<tr>内にあるので、find_all("tr")[0]として1個目の<tr>を取得し、find_all("th")で全ての<th>を取得しています。
days = soup.find("table", {"id": "infotablefont"}).find_all("tr")[0].find_all("th")

取得する日付のソース

citynameという名前のclassは一箇所でしか使われていないので、city = soup.find("th", {"class": "cityname"}).textで場所を取得します。.textを指定することで不要なタグを除いたテキストのみを取得します。

最高気温は、5個目の<tr>内にあるので、find_all("tr")[4]として5個目の<tr>を取得し、find_all("td")で全ての<td>を取得しています。
max_temp = soup.find("table", {"id": "infotablefont"}).find_all("tr")[4].find_all("td")

取得する最高気温のソース

最低気温は、6個目の<tr>内にあるので、find_all("tr")[5]として6個目の<tr>を取得し、find_all("td")で全ての<td>を取得しています。
min_temp = soup.find("table", {"id": "infotablefont"}).find_all("tr")[5].find_all("td")

取得する最低気温のソース

取得した要素の整形

日付・曜日を取得します。
はじめに空のリストを生成して、取得した情報から一件づつ日付・曜日をアペンドします。
day = day.textでテキスト情報のみを取得します。
ここで取得した日付と曜日は「11木」の様に日付と曜日が続いてしまうので、weeklist.append(day[-1])として最後の1文字の曜日のみを取得します。
日付部分を取得するには、daylist.append(day[:-1])として最後の1文字を除いて日付を取得します。
取得した情報には最初に「日付」という文字が入ってしまっているので、if '日付' not in day:として日付と曜日のみを取得しています。

daylist = []
weeklist = []
for day in days:
    day = day.text

    if '日付' not in day:
        weeklist.append(day[-1])
        daylist.append(day[:-1])

最高気温と最低気温を取得します。
はじめに空のリストを生成して、取得した情報から一件づつ気温をアペンドします。
maxtemp = maxtemp.text、mintemp = mintemp.textの部分で気温のテキストを取得します。
maxtemp、mintemp共に.replace('\n', '').replace('\t', '').replace('(', '{').replace(')', '}')として、不要なスペースの削除や文字列の変換を行います。ここで取得した情報は「17(15~19)」の様に複数の値が含まれているので、()内の情報を削除するために()を{}に変換しています。
maxtemp = re.sub('{.*?}', '', maxtemp)、mintemp = re.sub('{.*?}', '', mintemp)で{}内の情報を削除しています。
時々、取得した気温の部分が「/」になっている場合があるので、if '/' in maxtemp:として値が「/」だったらNoneに置き換えています。
最後に整形した情報をint()で数値に変換してアペンドします。

# 最高気温

maxtemplist = []
for maxtemp in max_temp:
    maxtemp = maxtemp.text

    if '最高' not in maxtemp:
        maxtemp = maxtemp.replace('\n', '').replace('\t', '').replace('(', '{').replace(')', '}')
        maxtemp = re.sub('{.*?}', '', maxtemp)

        if '/' in maxtemp:
            maxtemp = None
        else:
            maxtemp = int(maxtemp)

        maxtemplist.append(maxtemp)
# 最低気温

mintemplist = []
for mintemp in min_temp:
    mintemp = mintemp.text

    if '最低' not in mintemp:
        mintemp = mintemp.replace('\n', '').replace('\t', '').replace('(', '{').replace(')', '}')
        mintemp = re.sub('{.*?}', '', mintemp)

        if '/' in mintemp:
            mintemp = None
        else:
            mintemp = int(mintemp)

        mintemplist.append(mintemp)

最終的なコード

# scraping_weather.py

import re
import urllib.request

from bs4 import BeautifulSoup

url = urllib.request.urlopen('https://www.jma.go.jp/jp/week/315.html')
soup = BeautifulSoup(url, 'lxml')

city = soup.find("th", {"class": "cityname"}).text
days = soup.find("table", {"id": "infotablefont"}).find_all("tr")[0].find_all("th")
max_temp = soup.find("table", {"id": "infotablefont"}).find_all("tr")[4].find_all("td")
min_temp = soup.find("table", {"id": "infotablefont"}).find_all("tr")[5].find_all("td")

weather = []

daylist = []
weeklist = []
for day in days:
    day = day.text

    if '日付' not in day:
        weeklist.append(day[-1])
        daylist.append(day[:-1])

maxtemplist = []
for maxtemp in max_temp:
    maxtemp = maxtemp.text

    if '最高' not in maxtemp:
        maxtemp = maxtemp.replace('\n', '').replace('\t', '').replace('(', '{').replace(')', '}')
        maxtemp = re.sub('{.*?}', '', maxtemp)

        if '/' in maxtemp:
            maxtemp = None
        else:
            maxtemp = int(maxtemp)

        maxtemplist.append(maxtemp)

mintemplist = []
for mintemp in min_temp:
    mintemp = mintemp.text

    if '最低' not in mintemp:
        mintemp = mintemp.replace('\n', '').replace('\t', '').replace('(', '{').replace(')', '}')
        mintemp = re.sub('{.*?}', '', mintemp)

        if '/' in mintemp:
            mintemp = None
        else:
            mintemp = int(mintemp)

        mintemplist.append(mintemp)

weather.append(city)
weather.append(weeklist)
weather.append(daylist)
weather.append(maxtemplist)
weather.append(mintemplist)

print(weather)

出力結果

['前橋', ['木', '金', '土', '日', '月', '火', '水'], ['11', '12', '13', '14', '15', '16', '17'], [24, 24, 31, 29, 26, 29, 27], [18, 17, 21, 21, 20, 22, 21]]
ファントムYouTubeチャンネル

株式会社ファントムへのお問い合わせ

群馬県でPythonを使ったAIやソフトウェアを開発している株式会社ファントムが運営しています。




    press
    • Beautiful Soup
    • Share Article:
    • Twitter
    • Facebook
    • Pinterest
    • LinkedIn
    • Reddit
    Show Comments (2)

    Comments

    • Pythonistaを使って最高気温と最低気温をグラフ化 – Fantom blog

      […] 気象庁の天気予報をBeautifulSoup4でスクレイピング […]

      • 2019年7月11日
      • Article Author
      • ログインして返信する
    • def文を用いて共通の処理を関数化する – Fantom blog

      […] 気象庁の天気予報をBeautifulSoup4でスクレイピング […]

      • 2019年7月15日
      • Article Author
      • ログインして返信する

    Cancel Reply

    コメントを投稿するにはログインしてください。

    Related Articles

    Python

    iPhoneで撮影した写真をPythonでpngに変換

    iPhoneで撮影した写真をPythonでpngに変換 iPhoneで撮影した写真はHEICという拡張子で保存されます。この画像を利用したり編集したりするにはpngなどの形式に変換が必要なので画像が大量にある場合は1枚1 […]

    Posted on 5th 9月 2022 by press
    Python

    Beautiful Soupでoptionタグのvalueを取得する

    Beautiful Soupで以下のようなHTMLのoptionタグのvalueを取得する方法です。 optionタグのvalueの値を取得する方法 soup = soup.find_all('option')optio […]

    Posted on 15th 6月 2019 by press