WebページのHTMLの指定した<h5>タグの配下の、<div>タグの中のデータを取得するプログラムを作成しましたので、記録として残しておきます。
<h5 class="alert_h5">○○○の件名</h5> <div class="dit_a"> <p>【重要】(○○○)<br> 【重要・緊急】○○○のお知らせ<br> 【○○○】○○○等の確認について<br> <br> ※○○○<br></font></p> </div>
1.作成したPythonプログラム
以下作成したサンプルプログラムです。
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import requests
import re
from bs4 import BeautifulSoup
# Set the day before yesterday's date
beforeyesterday = datetime.now() - timedelta(days=15)
beforeyesterday_str = beforeyesterday.strftime("%Y%m%d")
mail_line_pattern = "From: \"[a-zA-Z0-9_.+-]+.+[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+\""
mail_pattern = "^[0-9a-zA-Z_.+-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z-.]+$"
env_mail_pattern = "<+[0-9a-zA-Z_.+-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z-.]+>"
subject_line_pattern = "Subject:"
# Initialize an empty list to store the articles
articles_beforeyesterday = []
text_beforeyesterday = []
link_beforeyesterday = []
mail_list = []
email_list = []
env_email_list = []
subject_list = []
title_list = []
# URL of the top page
url = "https://www.xxx.jp/news/"
domain ="http://www.xxx.jp"
# Get the HTML content of the top page
response = requests.get(url)
html = response.content.decode("utf-8")
# Use BeautifulSoup to parse the HTML content
soup = BeautifulSoup(html, "html.parser")
# Find all <a href> elements in the HTML
for a in soup.find_all("a",href=re.compile(beforeyesterday_str)):
if a in articles_beforeyesterday:
print("duplicated")
else:
text=a.getText()
link=a.get("href")
articles_beforeyesterday.append(a)
text_beforeyesterday.append(text)
link_beforeyesterday.append(link)
print(link_beforeyesterday)
for link in link_beforeyesterday:
# Get the HTML content of the top page
if link.startswith('http'):
print(link)
else:
link = domain + link
print(link)
response = requests.get(link)
html = response.content.decode("utf-8")
# Use BeautifulSoup to parse the HTML content
soup = BeautifulSoup(html, "html.parser")
h5_tags = soup.find_all('h5', class_='alert_h5')
for tag in h5_tags:
if tag.get_text() == '○○○の件名':
print(tag.find_next('p').get_text())
2.プログラムの解説
今回のポイントは2つあります。
データが指定した文字で始まっているか確認
1つ目は53 から57行目になります。
「if link.startswith(‘http’):」でlinkに入っているデータが’http’で始まっている場合、printしているだけですが、始まっていない場合、”http://www.xxx.jp”というデータを頭にくっつけています。
これは今回対象となったサイトのリンクがいきなりディレクトリで始まっていた為です。
指定したデータが含まれるタグ配下のデータを取得
2つ目のポイントは最後の4行になります。
「○○○の件名」が含まれる “h5″タグを見つけて、その配下の “p”タグで囲まれた文字列をピックアップしています。
3.実行結果
このプログラムの実行結果(出力)例は以下の通りです。
duplicated ['/news/xxxxxx_20230728.html', 'http://www.xxx.jp/news/xxxxx_20230728.html'] http://www.xxx.jp/news/xxxxxx_20230728.html 【重要】(○○○) 【重要・緊急】○○○のお知らせ 【○○○】○○○等の確認について ※○○○ http://www.xxx.jp/news/xxxxxx_20230728.html 【重要】(○○○) 【重要・緊急】○○○のお知らせ 【○○○】○○○等の確認について ※○○○

