0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

☑️総務省の消費者物価指数レポートを取得する

Last updated at Posted at 2024-08-20

総務省は下記のページで消費者物価指数に関するレポートを毎月掲載しています。
この記事では総務省の消費者物価指数レポートを全て取得するpythonコードを記載します。

ステップ1.メインページの内容を取得

上記のページはメインページになり各月ごとのページリンクがあります。そして各月ごとのリンク先にpdfが掲載されています。

select()メソッドを使って、a.stat-item_childというCSSセレクタを指定して、すべての月のリンクを取得します。

ステップ2.PDFリンクと公開日を取得

取得した各月のリンクをたどり、そのページからPDFリンクと公開日を取得します。link['href']でリンクのhref属性(相対URL)を取得し、ベースURLと組み合わせて完全なURLを作成します。

公開日はfind_next_sibling(text=True)を使って抽出します

PDFリンクはクラス名"stat-dl_icon stat-icon_2 stat-icon_format js-dl stat-download_icon_left"を持つ<a>タグを探し、そのhref属性を取得します。

コード

import requests
from bs4 import BeautifulSoup

# メインページのURL
main_url = 'https://www.e-stat.go.jp/stat-search/files?page=1&layout=datalist&toukei=00200573&tstat=000001150147&cycle=1&tclass1=000001150149&tclass2val=0'

# ページの内容を取得
response = requests.get(main_url)
response.raise_for_status()

# BeautifulSoupでHTMLを解析
soup = BeautifulSoup(response.content, 'lxml')

# 全ての月リンクを取得
month_links = soup.select('a.stat-item_child')

# ベースURL
base_url = 'https://www.e-stat.go.jp'

# 各月のページに移動してPDFリンクと公開日を取得
for link in month_links:
    month_url = base_url + link['href']
    
    month_response = requests.get(month_url)
    month_response.raise_for_status()

    # 月ごとのページを解析
    month_soup = BeautifulSoup(month_response.content, 'lxml')

    # 公開日を探す
    publish_date_tag = month_soup.find('span', class_='stat-sp', text='公開(更新)日  ')
    if publish_date_tag:
        publish_date = publish_date_tag.find_next_sibling(text=True).strip()
    else:
        publish_date = "公開日が見つかりませんでした"

    # PDFリンクを探す
    pdf_link_tag = month_soup.find('a', class_='stat-dl_icon stat-icon_2 stat-icon_format js-dl stat-download_icon_left')
    
    if pdf_link_tag:
        pdf_url = base_url + pdf_link_tag['href']
        print(f"公開日: {publish_date}, PDF URL: {pdf_url}")
    else:
        print(f"公開日: {publish_date}, No PDF found")
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?