1"""
2DMM.com Scraper — Core scraping logic.
3
4Extracts product data from DMM.com (Japan's largest e-commerce + digital content site).
5Categories: DVD, CD, electronics, books, games, and more.
6
7Data sources: GA4 embedded JSON, JSON-LD, HTML tables, Open Graph meta tags.
8"""
9from __future__ import annotations
10
11import concurrent.futures
12import json
13import re
14import time
15from dataclasses import dataclass, asdict
16from typing import Any
17
18import httpx
19
20BASE_URL = "https://www.dmm.com"
21UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0"
22HEADERS = {
23 "User-Agent": UA,
24 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
25 "Accept-Language": "ja-JP,ja;q=0.9,en-US,en;q=0.5",
26 "DNT": "1",
27}
28CRAWL_DELAY = 1.0
29MAX_WORKERS = 8
30MAX_RETRIES = 2
31
32
33CATEGORIES = {
34 "dvd": {
35 "name": "DVD",
36 "list_url": "/mono/dvd/-/list/=/sort=ranking/",
37 "detail_prefix": "/mono/dvd/-/detail/=/cid=",
38 },
39 "cd": {
40 "name": "CD",
41 "list_url": "/mono/cd/-/list/=/sort=ranking/",
42 "detail_prefix": "/mono/cd/-/detail/=/cid=",
43 },
44 "dvd_ranking": {
45 "name": "DVD Ranking",
46 "list_url": "/mono/dvd/-/ranking/",
47 "detail_prefix": "/mono/dvd/-/detail/=/cid=",
48 },
49}
50
51
52def _clean(text: str) -> str:
53 return re.sub(r"\s+", " ", text).strip() if text else ""
54
55
56@dataclass
57class DMMItem:
58 """Normalized DMM.com product data."""
59 cid: str = ""
60 title: str = ""
61 category: str = ""
62 category2: str = ""
63 price_jpy: int | None = None
64 shipping: str = ""
65 maker: str = ""
66 series: str = ""
67 genre: str = ""
68 release_date: str = ""
69 cast: str = ""
70 director: str = ""
71 runtime: str = ""
72 description: str = ""
73 image_url: str = ""
74 review_star_avg: float | None = None
75 review_count: int | None = None
76 url: str = ""
77 scraped_at: str = ""
78
79 def to_dict(self) -> dict:
80 d = asdict(self)
81 d["scraped_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
82 return {k: v for k, v in d.items() if v is not None}
83
84
85
86
87def create_session(proxy: str | None = None) -> httpx.Client:
88 """Create HTTPX client for DMM.com. Uses provided proxy if given."""
89 return httpx.Client(headers=HEADERS, follow_redirects=True, timeout=30, proxy=proxy)
90
91
92def _retry_get(session: httpx.Client, url: str) -> httpx.Response | None:
93 for attempt in range(1, MAX_RETRIES + 1):
94 try:
95 resp = session.get(url)
96 if resp.status_code == 200:
97 return resp
98 time.sleep(2 * attempt)
99 except Exception:
100 time.sleep(2 * attempt)
101 return None
102
103
104
105
106def _parse_ga4_json(html: str) -> dict:
107 """Extract GA4 embedded product JSON."""
108 m = re.search(r'input[^>]*name="ga4SendProduct"[^>]*value="([^"]*)"', html)
109 if not m:
110 return {}
111 raw = m.group(1).replace(""", '"').replace(""", '"').replace("'", "'")
112 try:
113 return json.loads(raw)
114 except Exception:
115 return {}
116
117
118def _parse_json_ld(html: str) -> dict:
119 """Extract JSON-LD structured data."""
120 m = re.search(r'<script[^>]*type="application/ld\+json"[^>]*>(.*?)</script>', html, re.DOTALL)
121 if not m:
122 return {}
123 try:
124 clean = m.group(1).replace("\n", " ").replace("\r", " ")
125 return json.loads(clean)
126 except Exception:
127 return {}
128
129
130def _parse_detail_table(html: str, item: DMMItem) -> DMMItem:
131 """Parse the product detail table (発売日, メーカー, ジャンル, etc.)."""
132 rows = re.findall(r"<tr[^>]*>(.*?)</tr>", html, re.DOTALL)
133 for row in rows:
134 cells = re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row, re.DOTALL)
135 if len(cells) < 2:
136 continue
137 key = _clean(re.sub(r"<[^>]+>", "", cells[0]))
138 val = _clean(re.sub(r"<[^>]+>", "", cells[1]))
139 val = val.replace(" ", " ").replace("&", "&")
140
141 if not key or key in (" ", ""):
142 continue
143 if "発売日" in key:
144 item.release_date = val
145 elif "メーカー" in key:
146 item.maker = val
147 elif "シリーズ" in key:
148 item.series = val
149 elif "ジャンル" in key:
150 item.genre = val
151 elif "出演者" in key:
152 item.cast = val
153 elif "監督" in key:
154 item.director = val
155 elif "収録時間" in key or ("収録" in key and "時間" in key):
156 item.runtime = val
157
158 return item
159
160
161def scrape_detail(session: httpx.Client, cid: str, category: str = "dvd") -> DMMItem | None:
162 """Scrape a single DMM product detail page."""
163 cat_info = CATEGORIES.get(category, CATEGORIES["dvd"])
164 url = f"{BASE_URL}{cat_info['detail_prefix']}{cid}/"
165
166 resp = _retry_get(session, url)
167 if not resp:
168 return None
169 html = resp.text
170
171 item = DMMItem(cid=cid, url=url)
172
173
174 ga4 = _parse_ga4_json(html)
175 if ga4:
176 item.title = ga4.get("item_name", "")
177 item.category = ga4.get("item_category", "")
178 item.category2 = ga4.get("item_category2", "")
179 price_info = ga4.get("priceInfo", {})
180 if isinstance(price_info, dict):
181 item.price_jpy = price_info.get("price")
182 item.shipping = ga4.get("mono_shipping_tier", "")
183
184 reviews = ga4.get("review_star_avg")
185 if reviews is not None:
186 try:
187 item.review_star_avg = float(reviews)
188 except (ValueError, TypeError):
189 pass
190 rcount = ga4.get("review_comment_cnt")
191 if rcount is not None:
192 try:
193 item.review_count = int(rcount)
194 except (ValueError, TypeError):
195 pass
196
197
198 ld = _parse_json_ld(html)
199 if ld and not item.title:
200 item.title = ld.get("name", "")
201 if ld and not item.description:
202 item.description = _clean(ld.get("description", ""))[:3000]
203
204
205 if not item.image_url:
206 og_img = re.search(r'<meta[^>]*property="og:image"[^>]*content="([^"]*)"', html)
207 if og_img:
208 item.image_url = og_img.group(1)
209
210
211 if not item.title:
212 og_title = re.search(r'<meta[^>]*property="og:title"[^>]*content="([^"]*)"', html)
213 if og_title:
214 item.title = og_title.group(1)
215
216
217 if not item.description:
218 og_desc = re.search(r'<meta[^>]*property="og:description"[^>]*content="([^"]*)"', html)
219 if og_desc:
220 item.description = _clean(og_desc.group(1))[:3000]
221
222
223 item = _parse_detail_table(html, item)
224
225 return item
226
227
228
229
230def _extract_cids_from_html(html: str) -> list[str]:
231 """Extract all unique CIDs from a listing/ranking page."""
232 cids = re.findall(r"cid=([a-z0-9_]+)", html)
233 return list(dict.fromkeys(cids))
234
235
236def scrape_listing(session: httpx.Client, category: str = "dvd") -> list[str]:
237 """Scrape a listing page and return all CIDs."""
238 cat_info = CATEGORIES.get(category, CATEGORIES["dvd"])
239 url = f"{BASE_URL}{cat_info['list_url']}"
240 resp = _retry_get(session, url)
241 if not resp:
242 print(f" [DBG] listing returned None for {url}")
243 return []
244 html = resp.text
245 print(f" [DBG] listing {resp.status_code} len={len(html)} first200={html[:200]}")
246 return _extract_cids_from_html(html)
247
248
249
250
251def scrape_one(cid_and_cat: tuple[str, str], proxy: str | None = None) -> DMMItem | None:
252 """Thread-safe wrapper for concurrent scraping."""
253 cid, category = cid_and_cat
254 session = create_session(proxy)
255 return scrape_detail(session, cid, category)
256
257
258def scrape_many(cids: list[str], category: str, max_results: int, proxy: str | None = None) -> list[DMMItem]:
259 """Batch scrape products in parallel."""
260 if not cids:
261 return []
262 ids = cids[:max_results]
263 results: list[DMMItem] = []
264 params = [(cid, category) for cid in ids]
265
266 with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
267 fut_map = {pool.submit(scrape_one, p, proxy): p for p in params}
268 for future in concurrent.futures.as_completed(fut_map):
269 item = future.result()
270 if item:
271 results.append(item)
272 time.sleep(CRAWL_DELAY / MAX_WORKERS)
273
274 by_id = {r.cid: r for r in results}
275 return [by_id[cid] for cid in ids if cid in by_id]
276
277
278
279
280def scrape_category(
281 category: str = "dvd",
282 max_results: int = 50,
283 proxy: str | None = None,
284) -> list[DMMItem]:
285 """Scrape a DMM category ranking and return product details."""
286 session = create_session(proxy)
287 cids = scrape_listing(session, category)
288 return scrape_many(cids, category, max_results, proxy=proxy)
289
290
291def scrape_product_ids(cids: list[str], category: str = "dvd", proxy: str | None = None) -> list[DMMItem]:
292 """Scrape specific product CIDs."""
293 return scrape_many([c.strip() for c in cids if c.strip()], category, len(cids), proxy=proxy)