タイトルの通り、何かのhtml タグではなく、ブラウザに表示される文字列のスタート部分とエンド部分を指定して html データを抜き出してみました。
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=17)
beforeyesterday_str = beforeyesterday.strftime("%Y/%m/%d")
# URL of the top page
url = "https://www.xxx.jp/"・・・スクレイピングサイト"/"付き
domain ="https://www.xxx.jp"・・・スクレイピングサイト"/"無し
# start_string と end_string の間のストリングを取得する
start_string = "○○の一例:"
end_string = "○○○した場合は、○○○までご連絡ください。"
# 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 the parent element with the "○○○情報" title
security_info = soup.find('h1', string="○○○情報").parent
#print(security_info)
# Find all <h3> tags within the parent element
h3_tags = security_info.find_all('h3')
filtered_links = [tag.a['href'] for tag in h3_tags if tag.a is not None and beforeyesterday_str in tag.a.text]
for link in filtered_links:
if link.startswith('http'):
print(link)
else:
link = domain + link
print(link)
# トップページから取得した指定日の記事を読み込む
response = requests.get(link)
html = response.content.decode("utf-8")
# BeautifulSoupを使ってHTMLを解析
# soup = BeautifulSoup(html, 'html.parser')
# article = soup.find('article', class_="nc-content-list")
# print(article)
# texts_p = [c.get_text() for c in article.find_all('p')]
# print(texts_p)
# Split the target text on the start and end strings and take the middle part
target_text = html.split(start_string)[1].split(end_string)[0].split("</p>")[0]
print(target_text)
# 改行コードを空文字列に置換して一つのテキストにする
target_text = target_text.replace('\n', '')
# <br />タグを区切り文字として順番に配列に入れる
result_array = [text for text in target_text.split('<br />') if text]
# 結果の出力
print(result_array)
2.プログラムのポイント
ChatGPTと相談しながらつくったのではっきりわかってないところはありますが^^、大体以下の意味合いかと思います。
タグとストリングで検索し親タグを含めたデータを取得
# この方法<p>タグなどには使えないかもしれません。
27行目:security_info = soup.find(‘h1’, string=”○○○”).parent
これは”○○○”というストリングが含まれる<h1>タグを見つけて、その1つ上位層のタグまでのデータをsecurity_infoに渡してくれているようです。
31行目:h3_tags = security_info.find_all(‘h3’)
21行目のsecurity_infoから<h3>タグの部分だけ抜き出してh3_tagsに入れてくれているようです。
33行目:filtered_links = [tag.a[‘href’] for tag in h3_tags if tag.a is not None and beforeyesterday_str in tag.a.text]
ここやたら長いですが、結果的には
h3_tagsからbeforeyesterday_strが含まれるhrefのリンクデータのみ抜き出し、filtered_linksに入れてくれているようです。
スタートとエンドの文字列を指定して抜き出し、お尻の不要なデータを削除
57行目:target_text = html.split(start_string)[1].split(end_string)[0].strip().split(“</p>”)[0]
ここも長いですが、
htmlに読み込まれているWebページのデータについて、start_string から end_stringまでのデータを抜き出してくれているようです。
また、split(“</p>”)[0]をつけることで、お尻にくっついていた</p>タグ以降を削除しています。
3.実行例
以下、実際にプログラムを実行した際の出力結果です。
https://web.xxx.jp/faqs/xxxx ○○○のサイズがクォータ制限に達しました<br />○○○のストレージ容量が少ない<br />~ 受信メールエラー<br />○○○のストレージがいっぱいです、○○○が一時停止されています ['○○○のサイズがクォータ制限に達しました', '○○○のストレージ容量が少ない', '~ 受信メールエラー', '○○○のストレージがいっぱいです、○○○が一時停止されています']

