
AI備忘録
スタジオ

リコール情報取得Excel取得全件



import re
BASE = "https://www.meti.go.jp/product_safety/recall/"
def main(url_text: str, done_urls: str, limit: int) -> dict:
limit = max(1, min(int(limit or 10), 30)) # 配列の上限(30件)に合わせる
pat = r"file/(\d{6}-\d+\.html)"
done = set(re.findall(pat, done_urls or ""))
seen, ids = set(), []
for f in re.findall(pat, url_text or ""): # 貼り付けた順
if f not in seen:
seen.add(f); ids.append(f)
todo = [f for f in ids if f not in done]
picked = [BASE + "file/" + f for f in todo[:limit]]
# 貼り付けた順のまま処理する(並びはExcelで決める)
notes = "貼り付け %d件 / 取得済み除外 %d件 / 今回の対象 %d件" % (len(ids), len(ids) - len(todo), len(picked))
if not ids:
notes = "URLが見つかりません。file/260101-1.html のような形のURLを貼ってください"
return {"urls": picked, "count": len(picked), "notes": notes}


import time
def main(url: str) -> dict:
time.sleep(10) # 待機する秒数。サイトへの負担を減らすため(10秒以内にしてください)
return {"url": url}

import re
import unicodedata
from html.parser import HTMLParser
# ===== 設定 =====
COLS = ["S番号","C番号","リコール実施日","リコール実施の理由","リコール事業者名","法人番号",
"製品名","商品名","JANコード","品番","型番","製造期間","数量",
"色","サイズ","ブランド","OEM","ロットNo","製造番号","備考",
"その他","詳細URL","最終更新日","要確認"]
HALF_COLS = {"リコール実施日","最終更新日","製造期間","詳細URL"} # 数字を半角で持つ列
QTY_COL = "数量"
HEADER_MAP = [("ブランド","ブランド"),("OEM","OEM"),("製造元","OEM"),("製造事業者","OEM"),
("ロット","ロットNo"),("LOT","ロットNo"),("Lot","ロットNo"),
("製造番号","製造番号"),("シリアル","製造番号"),("製造No","製造番号"),("製番","製造番号"),
("備考","備考"),("注記","備考"),("特記","備考"),
("サイズ","サイズ"),("寸法","サイズ"),("色","色"),("カラー","色"),
("商品名","商品名"),("品名","商品名"),("名称","商品名"),("JAN","JANコード"),
("品番","品番"),("型番","型番"),("型式","型番"),("記号","型番"),
("製造期間","製造期間"),("販売期間","製造期間"),("期間","製造期間"),
("台数","数量"),("数量","数量"),("個数","数量"),("枚数","数量"),("対象数","数量")]
# ===== 表記の統一 =====
def to_full(s):
s = re.sub(r"[\uFF61-\uFF9F]+", lambda m: unicodedata.normalize("NFKC", m.group()), s)
return "".join("\u3000" if c == " " else chr(ord(c) + 0xFEE0) if "!" <= c <= "~" else c for c in s)
def digits_half(s):
return s.translate({0xFF10 + i: 0x30 + i for i in range(10)})
def parse_qty(v):
if v is None or v == "": return "", None
if isinstance(v, (int, float)): return int(v), None
t = unicodedata.normalize("NFKC", str(v)).replace(",", "")
if re.search(r"[千百億兆]", t): return "", "数量:数値にできず(原文「%s」)" % v
t = re.sub(r"(\d+(?:\.\d+)?)万(\d+)?", lambda m: str(int(float(m.group(1)) * 10000) + int(m.group(2) or 0)), t)
nums = re.findall(r"\d+(?:\.\d+)?", t)
if len(nums) == 1: return int(float(nums[0])), None
return "", "数量:数値にできず(原文「%s」)" % v
def normalize_record(r):
r = dict(r); flags = [f for f in (r.get("要確認") or "").split("; ") if f]
for k, v in list(r.items()):
if k == QTY_COL:
r[k], note = parse_qty(v)
if note: flags.append(note)
elif isinstance(v, str):
if k == "詳細URL": continue
v = to_full(v)
r[k] = digits_half(v) if k in HALF_COLS else v
r["要確認"] = "; ".join(dict.fromkeys(flags))
return r
# ===== 表のパース(rowspan/colspan対応) =====
class TableParser(HTMLParser):
def __init__(self):
super().__init__(); self.tables = []; self.cur = None; self.row = None; self.cell = None
def _close_cell(self):
if self.cell is not None and self.row is not None: self.row.append(self.cell)
self.cell = None
def _close_row(self):
self._close_cell()
if self.row and self.cur is not None: self.cur.append(self.row)
self.row = None
def handle_starttag(self, tag, attrs):
a = dict(attrs)
if tag == "table": self.cur = []
elif tag == "tr" and self.cur is not None: self._close_row(); self.row = []
elif tag in ("td", "th") and self.row is not None:
self._close_cell() # 終了タグが省略された古いHTML対策
def n(k):
try: return max(1, int(a.get(k, 1)))
except Exception: return 1
self.cell = {"t": "", "rs": n("rowspan"), "cs": n("colspan")}
elif tag == "br" and self.cell is not None: self.cell["t"] += "\n"
def handle_endtag(self, tag):
if tag in ("td", "th"): self._close_cell()
elif tag == "tr": self._close_row()
elif tag == "table" and self.cur is not None:
self._close_row(); self.tables.append(self.cur); self.cur = None
def handle_data(self, d):
if self.cell is not None: self.cell["t"] += d
def grid(rows):
out, pend = [], {}
for r in rows:
line, c, it = [], 0, iter(r)
while True:
if c in pend and pend[c][0] > 0:
n, t = pend[c]; line.append((t, True)); pend[c] = (n - 1, t); c += 1; continue
cell = next(it, None)
if cell is None: break
t = re.sub(r"[ \u3000\t]+", " ", cell["t"]).strip()
for _ in range(cell["cs"]):
line.append((t, False))
if cell["rs"] > 1: pend[c] = (cell["rs"] - 1, t)
c += 1
out.append(line)
return out
ANN_RE = re.compile(r"^[((]([^::))]+)[::]\s*(.+?)[))]$") # 例: (ブランド名:Panasonic)
def lines(s): return [x.strip() for x in s.split("\n") if x.strip()]
TOTAL_WORDS = {"合計", "総計", "計", "合計台数"}
def expand(g):
header = [h for h, _ in g[0]]; last = [""] * len(header); recs = []; totals = []
for row in g[1:]:
first = re.sub(r"[\s\u3000]", "", row[0][0]) if row else ""
if first in TOTAL_WORDS: # 合計の行はレコードにしない(合計は、あとで備考に残す)
vals = [t for t, _ in row if t and re.sub(r"[\s\u3000]", "", t) not in TOTAL_WORDS]
if vals: totals.append(re.sub(r"[^0-9]", "", vals[-1]))
continue
cells = []
for ci, (t, merged) in enumerate(row[:len(header)]):
note = ""
if not t and last[ci]: t, note = last[ci], "carry"
elif t: last[ci] = t
ls = lines(t)
if "期間" in header[ci] and len(ls) > 1 and any(re.fullmatch(r"[~〜~--]", x) or x.endswith(("~", "〜", "~")) or x.startswith(("~", "〜", "~")) for x in ls):
ls = ["".join(ls)] # 例: 1998年8月 / ~ / 1999年12月 → 1つの期間
cells.append((ls, note))
ann = {} # 括弧書きの注記(ブランド名など)は行全体の共通値にする
cells2 = []
for v, note in cells:
keep = []
for ln in v:
m = ANN_RE.match(ln)
if m: ann.setdefault(m.group(1).strip(), m.group(2).strip())
else: keep.append(ln)
cells2.append((keep, note))
cells = cells2
n = max([len(v) for v, _ in cells] or [1]) or 1
for i in range(n):
rec, flag = {}, []
for k, val in ann.items(): rec.setdefault(k, val)
for h, (v, note) in zip(header, cells):
if len(v) == n: rec[h] = v[i]
elif len(v) == 1: rec[h] = v[0]
elif not v: rec[h] = ""
else: rec[h] = "".join(v); flag.append("%s:%d行を結合して共通値に(件数%d≠%d)" % (h, len(v), len(v), n))
if note == "carry": flag.append("%s:空欄を補完" % h)
recs.append((rec, list(dict.fromkeys(flag))))
if totals and totals[-1]:
key = "備考" if "備考" not in header else "合計"
for rec, _ in recs: rec.setdefault(key, "合計:" + totals[-1])
return recs
# ===== 詳細ページ =====
def strip_tags(s):
s = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", "", s)
s = re.sub(r"<br\s*/?>", "\n", s); s = re.sub(r"<[^>]+>", "", s)
s = s.replace(" ", " ").replace("&", "&")
return "\n".join(x.strip() for x in s.split("\n") if x.strip())
LABELS = ["リコール実施日","製品名","リコール事業者名","リコール実施の理由","リコール対策内容","リコールの対策内容",
"リコールの内容","リコール製品の概要","対象製品の外観","対象製品の確認方法","対策内容",
"事業者問い合わせ先","事業者リコール情報URL"]
def sections_by_h2(html):
out = {}
for p in re.split(r"<h2[^>]*>", html)[1:]:
title, _, body = p.partition("</h2>")
out[strip_tags(title)] = body
return out
def sections_by_label(html): # <h2>以外(h3、表の見出しなど)のページ用
hits = []
for lb in LABELS:
m = re.search(r">\s*" + re.escape(lb) + r"\s*<", html)
if m: hits.append((m.start() + 1, m.end() - 1, lb)) # (見出し文字の開始, 値の開始, 見出し)
hits.sort()
out = {}
for i, (ts, vs, lb) in enumerate(hits):
end = hits[i + 1][0] if i + 1 < len(hits) else len(html)
out[lb] = html[vs:end]
return out
def sections(html):
out = sections_by_h2(html)
if not (out.get("リコール実施日") or out.get("製品名")):
out = sections_by_label(html)
if "リコール製品の概要" not in out and "リコールの内容" in out:
out["リコール製品の概要"] = out["リコールの内容"] # 古いページの見出し
return out
def map_header(h):
for k, v in HEADER_MAP:
if k in h: return v
return None
def parse_detail(html, url):
sec = sections(html)
g = lambda k: strip_tags(sec.get(k, "")).replace("\n", " ")
firm = g("リコール事業者名"); m = re.search(r"[((]法人番号[::]\s*(\d+)[))]", firm)
corp = m.group(1) if m else ""
firm = re.sub(r"[((]法人番号[::][^))]*[))]", "", firm).strip()
upd = re.search(r"(?:最終更新日|リコール情報更新日)[::\s]*(\d{4}年\d{1,2}月\d{1,2}日)", strip_tags(html))
case = {"リコール実施日": g("リコール実施日"), "リコール実施の理由": g("リコール実施の理由"),
"リコール事業者名": firm, "法人番号": corp, "製品名": g("製品名"),
"詳細URL": url, "最終更新日": upd.group(1) if upd else ""}
tp = TableParser(); tp.feed(sec.get("リコール製品の概要", ""))
recs = []
if not tp.tables:
return [dict(case, 要確認="概要の表なし")]
for tbl in tp.tables:
G = grid(tbl)
if len(G) < 2: continue
for rec, flag in expand(G):
r = dict(case); other = []
for h, val in rec.items():
tgt = map_header(h)
if tgt and not r.get(tgt): r[tgt] = val
elif val: other.append("%s:%s" % (h, val))
if r.get("JANコード"):
r["JANコード"] = re.sub(r"[\s\u3000]+", "", r["JANコード"]) # 例: 87 10103 094005 → 8710103094005
if not r["JANコード"].upper().startswith("JAN"):
r["JANコード"] = "JAN" + r["JANコード"]
r["その他"] = " / ".join(other); r["要確認"] = "; ".join(flag)
recs.append(r)
return recs or [dict(case, 要確認="概要の表が空")]
# ===== Difyのコードノードの入口(反復の中で使う) =====
def main(html: str, url: str, status: int = 0) -> dict:
st = int(status or 0)
if not (html or "").strip() or (st and st != 200): # 空、または200以外 = サイトの確認画面などで取得できていない
why = "HTTP %s・本文%d文字(サイトの確認画面の可能性)" % (st or "不明", len(html or ""))
return {"rows": "!取得失敗\t" + why + "\t" + (url or ""), "count": 0}
recs = parse_detail(html or "", url or "")
if len(recs) == 1 and not recs[0].get("製品名") and not recs[0].get("リコール実施日"): # 見出しが1つも読めない
titles = [re.sub(r"\s+", " ", strip_tags(x)) for x in re.findall(r"<h[1-4][^>]*>(.*?)</h[1-4]>", html, flags=re.S)][:8]
txt = re.sub(r"\s+", " ", strip_tags(html))[:100]
hint = " / 文字化けの可能性(文字コードがShift_JISなど)" if ("\ufffd" in html or not re.search(r"[ぁ-ん]", strip_tags(html))) else ""
why = "解析できず(HTTP %s / HTML %d文字%s / 見出し: %s / 先頭: %s)" % (st or "不明", len(html), hint, " | ".join(titles), txt)
return {"rows": "!取得失敗\t" + why + "\t" + (url or ""), "count": 0}
rows = []
for r in recs:
r = normalize_record(dict(r)) # S番号・C番号は最後のノードで付ける
rows.append("\t".join(str(r.get(h, "")).replace("\t", " ").replace("\n", " ") for h in COLS))
return {"rows": "\n".join(rows), "count": len(rows)}
COLS = ['S番号', 'C番号', 'リコール実施日', 'リコール実施の理由', 'リコール事業者名', '法人番号', '製品名', '商品名', 'JANコード', '品番', '型番', '製造期間', '数量', '色', 'サイズ', 'ブランド', 'OEM', 'ロットNo', '製造番号', '備考', 'その他', '詳細URL', '最終更新日', '要確認']
def to_full(s):
return "".join("\u3000" if c == " " else chr(ord(c) + 0xFEE0) if "!" <= c <= "~" else c for c in s)
def main(pages: list, s_start: int, c_start: int) -> dict:
s_no = int(s_start or 1); c_no = int(c_start or 1)
LIMIT = 78000 # 文字列の出力上限(80000)に余裕をもたせる
out, total, flagged, used_pages, cut, failed = [], len("\t".join(COLS)) + 1, 0, 0, None, []
log = []
for pi, page in enumerate(pages or [], 1):
rows = [l for l in str(page or "").split("\n") if l.strip()]
if not rows: continue
if rows[0].startswith("!取得失敗"): # 取得できなかったページは表に入れない(番号も使わない)
parts = rows[0].split("\t"); failed.append(parts[-1])
log.append("失敗 | " + parts[-1] + ((" | " + parts[1]) if len(parts) > 2 else "")); continue
c_label = to_full("C%05d" % c_no)
page_out, s_tmp = [], s_no
for line in rows:
cols = line.split("\t")
cols += [""] * (len(COLS) - len(cols))
cols[0] = to_full("S%05d" % s_tmp); cols[1] = c_label; s_tmp += 1
page_out.append("\t".join(cols))
size = sum(len(x) + 1 for x in page_out)
if total + size > LIMIT:
cut = pi; break # このページ以降は入りきらない
out += page_out; total += size
fl = sum(1 for x in page_out if x.split("\t")[len(COLS) - 1])
flagged += fl
log.append("%s | %s | %d件 | 要確認 %d件" % (c_label, page_out[0].split("\t")[COLS.index("詳細URL")], len(page_out), fl))
s_no = s_tmp; c_no += 1; used_pages += 1
tsv = "\n".join(out) # 見出しは付けない(Excelの「結果」シートに、すでにある)
notes = "%d ページ・%d 件を結合。要確認あり: %d 件。次のS番号: %d / 次のC番号: %d" % (used_pages, len(out), flagged, s_no, c_no)
if failed: notes += "。取得失敗 %d 件(表に含めていません。取得済みURLにも入れないでください): %s" % (len(failed), " ".join(failed))
if cut: notes += "。文字数の上限のため %d ページ目以降は含めていません(件数を減らして再実行してください)" % cut
return {"tsv": tsv, "count": len(out), "notes": notes, "log": "\n".join(log)}
