本記事では、経済産業省のウェブサイトから全ての鉱工業指数レポートのPDFリンクとその公開日を自動的に取得するPythonコードについて解説します。
ステップ1: メインページの内容を取得
まず、メインページから必要な情報を取得するために、requestsライブラリを使用してHTMLコンテンツをダウンロードします。次に、BeautifulSoupを用いてページのHTMLを解析し、必要なリンクを抽出します。
import requests
from bs4 import BeautifulSoup
# メインページのURL
url = 'https://www.meti.go.jp/statistics/tyo/iip/kako_press.html'
# ページの内容を取得
response = requests.get(url)
response.raise_for_status()
# BeautifulSoupでHTMLを解析
soup = BeautifulSoup(response.content, 'lxml')
ここでは、requests.get()でウェブページの内容を取得し、BeautifulSoupでその内容を解析しています。このステップにより、ページ上に存在するすべてのリンクや要素にアクセス可能な状態になります。
ステップ2: PDFリンクと公開日を取得
次に、特定のパターンに一致するリンクを抽出します。今回は、href属性に/reference/を含むリンクを対象にします。また、リンクから日付情報(年と月)を正規表現で抽出し、これをフォーマットして表示します。
import re
# href属性に'/reference/'を含むリンクをすべて取得
reference_links = soup.find_all('a', href=lambda href: href and '/reference/' in href)
# ベースURL
base_url = 'https://www.meti.go.jp/statistics/tyo/iip/'
# リンクをプリント
for link in reference_links:
pdf_url = base_url + link['href']
# 正規表現で日付部分を抽出
match = re.search(r'b\d{4}_(\d{6})', link['href']) # YYYYMM形式の6桁をキャプチャ
if match:
year_month = match.group(1)
year = year_month[:4] # 最初の4桁を年として取得
month = year_month[4:] # 残りの2桁を月として取得
formatted_date = f"{year}-{month}"
print(f"日付: {formatted_date} | URL: {pdf_url}")
ここでは、BeautifulSoupで取得したリンクから、/reference/という文字列を含むものをフィルタリングし、それらのリンクの中から特定のパターンに一致する日付を抽出しています。この日付とリンクをフォーマットし、ユーザーフレンドリーな形式で出力します。
出力例
コードを実行すると、次のような形式で日付とリンクが出力されます。
日付: 2024-01 | URL: https://www.meti.go.jp/statistics/tyo/iip/result/pdf/reference/b2020_202401refsj.pdf
この形式により、日付情報が一目で分かるだけでなく、リンク先へのアクセスも容易になります。データ解析や報告書作成時に非常に便利です。
コード全体
import requests
from bs4 import BeautifulSoup
import re
# メインページのURL
url = 'https://www.meti.go.jp/statistics/tyo/iip/kako_press.html'
# ページの内容を取得
response = requests.get(url)
response.raise_for_status()
# BeautifulSoupでHTMLを解析
soup = BeautifulSoup(response.content, 'lxml')
# href属性に'/reference/'を含むリンクをすべて取得
reference_links = soup.find_all('a', href=lambda href: href and '/reference/' in href)
# ベースURL
base_url = 'https://www.meti.go.jp/statistics/tyo/iip/'
# リンクをプリント
for link in reference_links:
pdf_url = base_url + link['href']
# 正規表現で日付部分を抽出
match = re.search(r'b\d{4}_(\d{6})', link['href']) # YYYYMM形式の6桁をキャプチャ
if match:
year_month = match.group(1)
year = year_month[:4] # 最初の4桁を年として取得
month = year_month[4:] # 残りの2桁を月として取得
formatted_date = f"{year}-{month}"
print(f"日付: {formatted_date} | URL: {pdf_url}")