rein0421 commited on
Commit
d9d9573
·
verified ·
1 Parent(s): bfea3ba

Upload maps2.py

Browse files
Files changed (1) hide show
  1. maps2.py +1194 -0
maps2.py ADDED
@@ -0,0 +1,1194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import csv
4
+ import json
5
+ import time
6
+ from bs4 import BeautifulSoup
7
+ from selenium.webdriver.chrome.options import Options
8
+ from selenium.webdriver.common.by import By # Byクラスをインポート
9
+ from selenium.webdriver.support.ui import WebDriverWait
10
+ from selenium.webdriver.support import expected_conditions as EC
11
+ from selenium.common.exceptions import NoSuchElementException, TimeoutException, StaleElementReferenceException, ElementClickInterceptedException
12
+ import re
13
+ from urllib.parse import urlparse, urljoin
14
+ import traceback # tracebackをインポート
15
+ import io
16
+ import contextlib
17
+ from datetime import datetime
18
+
19
+ # --- WebDriverの選択 ---
20
+ IN_COLAB = 'google.colab' in str(get_ipython()) if 'get_ipython' in globals() else False
21
+ if IN_COLAB:
22
+ print("Google Colab環境を検出。google_colab_selenium を使用します。")
23
+ try: import google_colab_selenium as gs
24
+ except ImportError: print("google_colab_seleniumが見つかりません。!pip install google-colab-selenium を実行してください。"); gs = None
25
+ else:
26
+ print("ローカル環境を検出。通常の selenium webdriver を使用します。")
27
+ from selenium import webdriver
28
+ gs = None
29
+ try:
30
+ from selenium.webdriver.chrome.service import Service as ChromeService
31
+ from webdriver_manager.chrome import ChromeDriverManager
32
+ except ImportError:
33
+ print("webdriver-manager が見つかりません。 `pip install webdriver-manager` を実行してください。")
34
+ ChromeService = None
35
+ ChromeDriverManager = None
36
+
37
+
38
+ # --- Helper Functions ---
39
+ def find_prefixed_data_string(data_structure):
40
+ """データ構造内から ")]}'\n" で始まる文字列を見つける(再帰的検索)"""
41
+ if isinstance(data_structure, str) and data_structure.startswith(")]}'\n"):
42
+ return data_structure
43
+ elif isinstance(data_structure, list):
44
+ for item in data_structure:
45
+ found = find_prefixed_data_string(item)
46
+ if found:
47
+ return found
48
+ elif isinstance(data_structure, dict):
49
+ for value in data_structure.values():
50
+ found = find_prefixed_data_string(value)
51
+ if found:
52
+ return found
53
+ return None
54
+
55
+ def find_details_data_by_id_or_heuristic(data_list, place_id=None):
56
+ """
57
+ JSONデータリストから詳細情報を含む可能性のあるリストを特定する。
58
+ place_idがあればそれを優先し、なければヒューリスティック(住所形式など)で探す。
59
+ """
60
+ if not isinstance(data_list, list):
61
+ return None
62
+
63
+ potential_candidates = []
64
+ for item in data_list:
65
+ # 詳細データは通常、要素数が比較的多いリスト形式
66
+ if not isinstance(item, list) or len(item) < 30:
67
+ continue
68
+
69
+ is_candidate = False
70
+ # place_id が指定されていれば、リスト内にそのIDが含まれるかチェック
71
+ if place_id and place_id in str(item):
72
+ is_candidate = True
73
+ # place_id がない場合は、住所らしき情報が含まれるかヒューリスティックにチェック
74
+ elif not place_id:
75
+ has_address_like = any(
76
+ isinstance(sub, str) and
77
+ ("〒" in sub or
78
+ any(k in sub for k in ["都", "道", "府", "県", "市", "区", "町", "村", "丁目", "番地", "号"]) or
79
+ re.search(r'\d+-\d+-\d+', sub))
80
+ for sub in item
81
+ )
82
+ if has_address_like:
83
+ is_candidate = True
84
+
85
+ if is_candidate:
86
+ potential_candidates.append(item)
87
+
88
+ if not potential_candidates:
89
+ return None
90
+
91
+ # 候補が1つならそれを返す
92
+ if len(potential_candidates) == 1:
93
+ return potential_candidates[0]
94
+
95
+ # 候補が複数ある場合、スコアリングで最もそれらしいものを選ぶ
96
+ best_candidate = None
97
+ max_score = -1
98
+
99
+ for candidate in potential_candidates:
100
+ score = len(candidate) # 要素数が多いほど詳細情報の可能性が高い
101
+ try:
102
+ # 特定のインデックスにリストが存在するか(構造的な特徴)
103
+ if any(isinstance(candidate[idx], list) and candidate[idx] for idx in [7, 13, 178] if idx < len(candidate)):
104
+ score += 50
105
+ # URLらしき文字列が含まれるか
106
+ if 7 < len(candidate) and isinstance(candidate[7], list) and len(candidate[7]) > 0 and isinstance(candidate[7][0], str) and candidate[7][0].startswith('http'):
107
+ score += 50
108
+ # 別の構造的な特徴
109
+ if 34 < len(candidate) and isinstance(candidate[34], list) and candidate[34]:
110
+ score += 30
111
+ except Exception:
112
+ # スコアリング中のエラーは無視
113
+ pass
114
+
115
+ if score > max_score:
116
+ max_score = score
117
+ best_candidate = candidate
118
+
119
+ return best_candidate
120
+
121
+
122
+ def is_domain_like(text):
123
+ """文字列がドメイン名らしい形式か簡易的に判定"""
124
+ if not isinstance(text, str): return False
125
+ text = text.strip().lower()
126
+ common_tlds = ['.com', '.jp', '.co.jp', '.net', '.org', '.info', '.biz']
127
+ # URLスキーマ、パス、特殊文字、全角文字、IPアドレス形式、前後のドット、連続ドットは除外
128
+ if re.search(r'^(https?|ftp)://|[/\\?#\s\u3000-\uFFFF:;@!$%^*()=+]', text): return False
129
+ if re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', text): return False
130
+ if text.startswith('.') or text.endswith('.') or '..' in text: return False
131
+ # ドットを含み、一般的なTLDで終わるかチェック
132
+ return '.' in text and any(text.endswith(tld) for tld in common_tlds)
133
+
134
+ def safe_get(data, index, default=None):
135
+ """ネストされたリストや辞書から安全に値を取得する"""
136
+ if isinstance(index, int):
137
+ try:
138
+ return data[index] if isinstance(data, list) and index < len(data) else default
139
+ except IndexError:
140
+ return default
141
+ elif isinstance(index, list): # インデックスのリストでネストされた要素を取得
142
+ current = data
143
+ for idx in index:
144
+ try:
145
+ if isinstance(current, list) and isinstance(idx, int) and idx < len(current):
146
+ current = current[idx]
147
+ elif isinstance(current, dict) and idx in current:
148
+ current = current[idx]
149
+ else:
150
+ return default # 途中でリスト/辞書でない、またはインデックス/キーが存在しない場合
151
+ except (IndexError, KeyError, TypeError):
152
+ return default # その他の予期せぬエラー
153
+ return current
154
+ elif isinstance(index, str): # 文字列インデックスは辞書のキーとして扱う
155
+ return data.get(index, default) if isinstance(data, dict) else default
156
+ return default
157
+
158
+
159
+ # --- HTML抽出関数 (本文抽出を span.wiI7pd 優先に変更) ---
160
+ def extract_details_and_reviews_from_html(html_content):
161
+ """詳細HTMLから基本情報と口コミ情報を抽出 (本文は span.wiI7pd 優先)"""
162
+ print(" [HTML Extractor - Details & Reviews (wiI7pd priority)] 開始")
163
+ soup = BeautifulSoup(html_content, 'lxml' if 'lxml' in globals() else 'html.parser')
164
+ details = {"name": "N/A", "url": "", "phone": "N/A", "address": "N/A", "links": {}, "reviews": [], "extraction_error": None}
165
+ try:
166
+ # --- 基本情報の抽出 ---
167
+ main_container_selector = '.aIFcqe'
168
+ main_container = soup.select_one(main_container_selector)
169
+ search_root = soup # デフォルトはページ全体
170
+ if main_container:
171
+ print(f" '{main_container_selector}' コンテナ発見。基本情報を抽出。")
172
+ search_root = main_container
173
+ else:
174
+ print(f" 警告: '{main_container_selector}' コンテナが見つかりません。ページ全体から基本情報を抽出。")
175
+
176
+ # 名前 (h1タグを探す)
177
+ name_tag = search_root.find('h1')
178
+ if name_tag:
179
+ details['name'] = name_tag.get_text(strip=True)
180
+ elif details['name'] == 'N/A': # フォールバックで<title>から取得
181
+ title_tag = soup.find('title')
182
+ if title_tag and title_tag.string:
183
+ title_text = title_tag.string.replace('- Google マップ', '').strip()
184
+ if title_text.lower() != "google マップ": details["name"] = title_text
185
+
186
+ # 電話、住所、ウェブサイトなどの情報を抽出
187
+ selectors_map = {
188
+ "phone": ['button[data-item-id^="phone:tel:"]', 'div.Io6YTe', 'button[aria-label*="電話番号"]'],
189
+ "address": ['button[data-item-id="address"]', 'div.rogA2c', 'button[aria-label*="住所"]'],
190
+ "website": ['a[data-item-id="authority"][href^="http"]', 'button[data-item-id="authority"]', 'a[aria-label*="ウェブサイト"][href^="http"]'],
191
+ "other_link": ['a.CsEnBe[href^="http"]'] # 公式サイト以外のリンク
192
+ }
193
+
194
+ for info_type, selectors in selectors_map.items():
195
+ found_val = None
196
+ for selector in selectors:
197
+ element = search_root.select_one(selector)
198
+ # コンテナ内で見つからなければページ全体で再検索
199
+ if not element and search_root != soup:
200
+ element = soup.select_one(selector)
201
+
202
+ if element:
203
+ data_item_id = element.get('data-item-id', '')
204
+ aria_label = element.get('aria-label', '')
205
+ element_text = element.get_text(strip=True)
206
+ href = element.get('href')
207
+
208
+ if info_type == "phone":
209
+ phone_num = None
210
+ if data_item_id.startswith('phone:tel:'): phone_num = data_item_id.split(':')[-1]
211
+ elif "電話番号:" in aria_label: phone_num = re.search(r'([\d-]+)', aria_label.split("電話番号:")[-1])
212
+ elif element.name == 'div' and re.match(r'^[\d\s-]+$', element_text): phone_num = element_text
213
+ # 電話番号形式の整形と検証
214
+ if isinstance(phone_num, str): phone_num = phone_num.strip()
215
+ elif hasattr(phone_num, 'group'): phone_num = phone_num.group(1).strip()
216
+ if phone_num and re.match(r'^[\d-]+$', phone_num.replace('ー','-')):
217
+ found_val = phone_num.replace('ー','-')
218
+ break # 電話番号が見つかったらループ脱出
219
+ elif info_type == "address":
220
+ addr_text = None
221
+ if data_item_id == 'address': addr_text = element_text
222
+ elif "住所:" in aria_label: addr_text = aria_label.split("住所:")[-1].split('(新しいウィンドウで開きます)')[0].strip()
223
+ elif element.name == 'div' and ("〒" in element_text or any(k in element_text for k in ["都","道","府","県","市","区","町","村"])): addr_text = element_text
224
+ # 住所らしき文字列か簡易チェック
225
+ if addr_text and len(addr_text) > 5: # ある程度の長さがあるか
226
+ found_val = addr_text
227
+ break # 住所が見つかったらループ脱出
228
+ elif info_type == "website" or info_type == "other_link":
229
+ if href and href.startswith('http') and 'google.com' not in urlparse(href).netloc: # Google自身のリンクは除外
230
+ link_name = "N/A"; is_website = False
231
+ # リンクの種類を判別
232
+ if data_item_id == 'authority' or "ウェブサイト" in aria_label:
233
+ link_name = element_text if is_domain_like(element_text) else "ウェブサイト"
234
+ is_website = True
235
+ elif info_type == "other_link":
236
+ link_name = f"リンク ({element_text})" if element_text else "外部リンク"
237
+ elif is_domain_like(element_text): # ドメイン名らしきテキストの場合
238
+ link_name = element_text
239
+
240
+ if link_name != "N/A":
241
+ normalized_url = href.rstrip('/')
242
+ # 重複を避けて links 辞書に追加
243
+ if not any(existing_url.rstrip('/') == normalized_url for existing_url in details["links"].values()):
244
+ details["links"][link_name] = href
245
+ # website タイプで見つかったものを優先的にメインURL候補へ (まだ未設定の場合)
246
+ if is_website and details["url"] == "":
247
+ details["url"] = href
248
+ # website タイプならこのセレクタでの探索は終了
249
+ if info_type == "website":
250
+ found_val = href # 見つかったことを示す
251
+ break # websiteセレクタのループ脱出
252
+
253
+ # 各タイプの最初の有効な値を details に格納 (other_link は除く)
254
+ if found_val and info_type in details and info_type != "other_link":
255
+ details[info_type] = found_val
256
+
257
+ # メインURLがまだ決まっていない場合、links 辞書から探す
258
+ if details["url"] == "":
259
+ priority = ["ウェブサイト", "authority"] # 公式サイトらしき名前を優先
260
+ found_url_in_links = False
261
+ for p_word in priority:
262
+ for name, url in details["links"].items():
263
+ if p_word in name.lower():
264
+ details["url"] = url
265
+ found_url_in_links = True
266
+ break
267
+ if found_url_in_links:
268
+ break
269
+ # それでも見つからなければ、ドメイン名らしきリンク > 最初のリンク
270
+ if not found_url_in_links:
271
+ domain_link = next((url for name, url in details["links"].items() if is_domain_like(name)), None)
272
+ if domain_link:
273
+ details["url"] = domain_link
274
+ elif details["links"]: # linksに何かあれば最初のものをURLとする
275
+ details["url"] = next(iter(details["links"].values()))
276
+ print(f" 基本情報抽出完了: Name='{details['name']}'")
277
+
278
+
279
+ # --- 口コミ情報の抽出 ---
280
+ print(" 口コミ情報抽出開始 (span.wiI7pd 優先)...")
281
+ review_container_selector = 'div.GHT2ce.NsCY4'
282
+ review_container = soup.select_one(review_container_selector)
283
+ if review_container:
284
+ print(f" '{review_container_selector}' 口コミコンテナ発見。")
285
+ # 口コミカードの特定 (jftiEf or MyEned)
286
+ review_card_selectors = ['div.jftiEf', 'div.MyEned']
287
+ review_cards = []
288
+ for sel in review_card_selectors:
289
+ review_cards = review_container.select(sel)
290
+ if review_cards:
291
+ print(f" 口コミカードセレクタ '{sel}' で {len(review_cards)} 件発見。")
292
+ break
293
+ if not review_cards:
294
+ print(" 警告: 口コミコンテナ内で口コミカードが見つかりません。")
295
+
296
+ extracted_reviews = []
297
+ for card_idx, card in enumerate(review_cards):
298
+ try:
299
+ review_text = "N/A"; reviewer_name = "N/A"; rating = "N/A"
300
+
301
+ # 口コミ本文抽出 (span.wiI7pd 優先)
302
+ text_span_wiI7pd = card.select_one('span.wiI7pd')
303
+ if text_span_wiI7pd:
304
+ review_text = text_span_wiI7pd.get_text(strip=True)
305
+ else:
306
+ # フォールバック: span[jscontroller="MZnM8e"]
307
+ full_text_span = card.select_one('span[jscontroller="MZnM8e"]')
308
+ if full_text_span:
309
+ review_text = full_text_span.get_text(strip=True)
310
+
311
+ # 投稿者名 (.d4r55)
312
+ name_el = card.select_one('.d4r55');
313
+ if name_el: reviewer_name = name_el.get_text(strip=True)
314
+
315
+ # 評価 (.kvMYJc aria-label)
316
+ rating_el = card.select_one('.kvMYJc');
317
+ if rating_el:
318
+ aria_label = rating_el.get('aria-label', '');
319
+ match = re.search(r'星 (\d+(\.\d+)?)', aria_label) # "星 5.0" などを想定
320
+ if match: rating = match.group(1)
321
+
322
+ # 情報が一部でも取れていれば追加
323
+ if review_text != "N/A" or reviewer_name != "N/A":
324
+ extracted_reviews.append({"reviewer": reviewer_name, "rating": rating, "text": review_text if review_text != "N/A" else ""})
325
+
326
+ except Exception as e_card:
327
+ print(f" 口コミカード {card_idx+1} の解析中にエラー: {e_card}")
328
+ extracted_reviews.append({"reviewer": "Error", "rating": "N/A", "text": f"解析エラー: {e_card}"})
329
+
330
+ details['reviews'] = extracted_reviews
331
+ print(f" 口コミ抽出完了: {len(details['reviews'])} 件")
332
+ else:
333
+ print(f" 警告: '{review_container_selector}' 口コミコンテナが見つかりません。")
334
+
335
+ except Exception as e_extract:
336
+ print(f"★★★★★ HTML抽出処理中にエラーが発生しました ★★★★★")
337
+ error_trace = traceback.format_exc()
338
+ print(error_trace)
339
+ details['extraction_error'] = f"Type: {type(e_extract).__name__}, Msg: {e_extract}\nTrace: {error_trace}"
340
+
341
+ print(f" [HTML Extractor - Details & Reviews (wiI7pd priority)] 完了: Name='{details['name']}'")
342
+ return details
343
+
344
+
345
+ # --- CSV Loading Function ---
346
+ def load_queries(csv_path):
347
+ """CSVファイルを読み込み、1列目のクエリをリストとして返す"""
348
+ queries = []
349
+ encodings_to_try = ['utf-8-sig', 'utf-8', 'cp932', 'shift_jis'] # 試すエンコーディングリスト
350
+ file_encoding = None
351
+ print(f"CSVファイル読み込み開始: {os.path.basename(csv_path)}")
352
+ if not csv_path or not os.path.exists(csv_path):
353
+ print("エラー: CSVファイルが見つかりません。")
354
+ return []
355
+
356
+ # ファイルのエンコーディングを特定
357
+ for encoding in encodings_to_try:
358
+ try:
359
+ with open(csv_path, 'r', encoding=encoding, errors='strict') as f:
360
+ f.read(1024) # ファイルの一部を読んでエンコーディングを確認
361
+ file_encoding = encoding
362
+ print(f" エンコーディング '{encoding}' で読み込み試行...")
363
+ break
364
+ except (UnicodeDecodeError, LookupError):
365
+ continue # 次のエンコーディングを試す
366
+ except Exception as e_enc:
367
+ print(f" '{encoding}' 試行中に予期せぬエラー: {e_enc}")
368
+ continue
369
+
370
+ if not file_encoding:
371
+ print(f"エラー: ファイル '{os.path.basename(csv_path)}' を読み込めるエンコーディングが見つかりません。")
372
+ return []
373
+
374
+ line_num = 0
375
+ try:
376
+ with open(csv_path, 'r', encoding=file_encoding, newline='') as f:
377
+ reader = csv.reader(f)
378
+ try:
379
+ header = next(reader) # 最初の行を読み込む
380
+ line_num += 1
381
+ print(f" 1行目 (ヘッダー可能性あり): {header}")
382
+ except StopIteration:
383
+ print("情報: CSVファイルが空です。")
384
+ return [] # ファイルが空なら終了
385
+
386
+ # 1行目がヘッダーかどうかを判定 (簡易的)
387
+ header_keywords = ['query', 'search', 'keyword', 'クエリ', '検索', 'キーワード', '店舗', '会社']
388
+ first_col_header = header[0].strip().lower() if header else ""
389
+ is_header = any(hkw in first_col_header for hkw in header_keywords)
390
+
391
+ # 1行目がヘッダーでなく、かつ内容があればクエリとして追加
392
+ if not is_header and header and header[0].strip():
393
+ queries.append(header[0].strip())
394
+ elif is_header:
395
+ print(" 1行目はヘッダーと判断しスキップします。")
396
+
397
+ # 2行目以降を処理
398
+ for row in reader:
399
+ line_num += 1
400
+ # 1列目にデータがあればクエリとして追加
401
+ if row and row[0].strip():
402
+ queries.append(row[0].strip())
403
+ # 1列目が空でも他の列にデータがあれば警告を表示 (スキップ対象)
404
+ elif any(cell.strip() for cell in row):
405
+ print(f"警告: 行 {line_num} の1列目が空です: {row}。スキップします。")
406
+
407
+ print(f" CSVから {len(queries)} 件の有効なクエリを抽出しました。")
408
+ except Exception as e:
409
+ # CSV処理中のエラーハンドリング
410
+ print(f"★★★★★ CSVファイル処理中にエラー (行 {line_num}) ★★★★★")
411
+ print(f"エラータイプ: {type(e).__name__}")
412
+ print(f"エラーメッセージ: {e}")
413
+ print("--- スタックトレース ---")
414
+ print(traceback.format_exc())
415
+ print("----------------------")
416
+ return [] # エラー発生時は空リストを返す
417
+ return queries
418
+
419
+
420
+ # --- Single Query Processing Function (「もっと見る」クリック追加, SyntaxError修正) ---
421
+ def process_single_query_full_list(driver, query, query_index, output_dir, wait_config):
422
+ """単一クエリ処理: 検索→リストスクロール→リンク抽出→詳細ページ→口コミタブ→口コミスクロール→「もっと見る」クリック→HTML取得→解析"""
423
+ print(f"\n--- クエリ処理開始 [Index:{query_index}] ---: {query}")
424
+ results_list = []
425
+ safe_query_part = re.sub(r'[\\/*?:"<>|]', '_', query)[:30].strip() or "empty_query"
426
+ base_url = "https://www.google.com/maps/"
427
+
428
+ # 待機時間設定
429
+ WAIT_TIME_BASE = wait_config['base']
430
+ WAIT_TIME_DETAIL = wait_config['detail']
431
+ WAIT_TIME_SEARCH = wait_config['search']
432
+ # スクロール設定
433
+ SCROLL_PAUSE_TIME = max(1.5, WAIT_TIME_BASE * 0.5)
434
+ MAX_SCROLL_ATTEMPTS = 30
435
+ SCROLL_PAUSE_TIME_REVIEW = max(1.0, WAIT_TIME_BASE * 0.3)
436
+ MAX_SCROLL_ATTEMPTS_REVIEW = 500 # 口コミは多い場合があるので回数を増やす
437
+ REVIEW_SCROLL_STUCK_LIMIT = 5 # 口コミスクロール停止判定の閾値
438
+
439
+ try:
440
+ # 1. 検索実行とリスト表示待機
441
+ search_url = f"https://www.google.com/maps/search/{query.replace(' ', '+')}"
442
+ print(f" URLにアクセス: {search_url}")
443
+ driver.get(search_url)
444
+ print(f" 検索結果リスト表示待機 (最大{WAIT_TIME_SEARCH}秒)...")
445
+ list_container_selector = 'div[role="feed"], div[aria-label*="の検索結果"]'
446
+ try:
447
+ list_container = WebDriverWait(driver, WAIT_TIME_SEARCH).until(
448
+ EC.presence_of_element_located((By.CSS_SELECTOR, list_container_selector))
449
+ )
450
+ # リスト内に最初の場所リンクが表示されるまで待つ
451
+ WebDriverWait(driver, 10).until(
452
+ EC.visibility_of_element_located((By.CSS_SELECTOR, f'{list_container_selector} a[href*="/maps/place/"]'))
453
+ )
454
+ print(" 検索結果リスト表示を確認。")
455
+ except TimeoutException as e_timeout:
456
+ # タイムアウトエラー処理
457
+ print(f" エラー: 検索結果リストの表示タイムアウト。URL: {search_url}\n{e_timeout}")
458
+ # ★★★ SyntaxError修正 ★★★
459
+ print("--- HTML Snapshot (Timeout) ---")
460
+ try:
461
+ print(driver.page_source[:1000]) # デバッグ用にHTMLの先��を表示
462
+ except Exception as e_snapshot:
463
+ print(f" ページソース取得失敗: {e_snapshot}")
464
+ print("--- End Snapshot ---")
465
+ results_list.append({'query_index': query_index, 'original_query': query, 'result_rank': 0, 'place_url': search_url, 'html_filename': 'N/A', 'name': f'Error (List Timeout)', 'url': '', 'phone': 'N/A', 'address': 'N/A', 'reviews': [], 'status': f'Error: List Timeout'})
466
+ return results_list # このクエリはこれ以上処理できない
467
+ except Exception as e_wait:
468
+ # その他のリスト待機エラー処理
469
+ print(f"★★★★★ リスト待機中に予期せぬエラー ★★★★★\nURL: {search_url}\n{type(e_wait).__name__}: {e_wait}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
470
+ results_list.append({'query_index': query_index, 'original_query': query, 'result_rank': 0, 'place_url': search_url, 'html_filename': 'N/A', 'name': f'Error (List Wait Exception)', 'url': '', 'phone': 'N/A', 'address': 'N/A', 'reviews': [], 'status': f'Error: List Wait Exception'})
471
+ return results_list # このクエリはこれ以上処理できない
472
+
473
+ # 2. 検索リストのスクロール
474
+ print(" 検索リストをスクロールして全結果を表示...")
475
+ last_height = driver.execute_script("return arguments[0].scrollHeight", list_container)
476
+ scroll_attempts = 0
477
+ stuck_count = 0
478
+ while scroll_attempts < MAX_SCROLL_ATTEMPTS:
479
+ try:
480
+ # スクロール実行
481
+ driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', list_container)
482
+ time.sleep(SCROLL_PAUSE_TIME)
483
+ # 新しい高さを取得
484
+ new_height = driver.execute_script("return arguments[0].scrollHeight", list_container)
485
+ # 終了マーカーを探す
486
+ end_markers = driver.find_elements(By.XPATH, "//span[contains(text(), '結果は以上です')] | //p[contains(text(), '結果は以上です')]")
487
+ if any(el.is_displayed() for el in end_markers):
488
+ print(" 「結果は以上です」表示確認。検索リストスクロール終了。")
489
+ break
490
+ # 高さが変わらなくなった場合の処理
491
+ if new_height == last_height:
492
+ stuck_count += 1
493
+ print(f" 検索リストスクロール高さ変化なし ({stuck_count}回目)。再試行...")
494
+ time.sleep(SCROLL_PAUSE_TIME * 1.5) # 少し長めに待つ
495
+ new_height = driver.execute_script("return arguments[0].scrollHeight", list_container) # 再確認
496
+ if new_height == last_height and stuck_count >= 3: # 3回連続で変化なければ終了と判断
497
+ print(" 高さ変化なしが続いたため、検索リストスクロール終了と判断。")
498
+ break
499
+ else:
500
+ stuck_count = 0 # 高さが変わればリセット
501
+ last_height = new_height
502
+ except Exception as e_scroll:
503
+ # スクロール中のエラー
504
+ print(f"★★★★★ 検索リストスクロール中にエラー ★★★★★\n{type(e_scroll).__name__}: {e_scroll}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
505
+ print(" スクロールエラー発生。可能な範囲で続行します。")
506
+ # スクロールエラーは致命的ではない場合もあるので続行
507
+ scroll_attempts += 1
508
+ if scroll_attempts >= MAX_SCROLL_ATTEMPTS:
509
+ print(f" 検索リスト最大スクロール回数 ({MAX_SCROLL_ATTEMPTS}) 到達。")
510
+
511
+ # 3. リンク抽出
512
+ print(" 検索結果リストからリンクを抽出...")
513
+ unique_place_links = set()
514
+ result_card_selector = '.hfpxzc' # メインのセレクタ
515
+ try:
516
+ # スクロール後にコンテナ要素を再取得
517
+ list_container_updated = WebDriverWait(driver, 10).until(
518
+ EC.presence_of_element_located((By.CSS_SELECTOR, list_container_selector))
519
+ )
520
+ # メインセレクタで要素を検索
521
+ result_cards = list_container_updated.find_elements(By.CSS_SELECTOR, result_card_selector)
522
+ print(f" '{result_card_selector}' 要素を {len(result_cards)} 件発見。")
523
+
524
+ # メインセレクタで見つからない場合の代替セレクタ試行
525
+ if not result_cards:
526
+ print(f" 警告: '{result_card_selector}' が見つかりません。代替セレクタ 'a.hfpxzc' で試行...")
527
+ result_card_selector = 'a.hfpxzc' # aタグ自体がクラスを持つ場合
528
+ result_cards = list_container_updated.find_elements(By.CSS_SELECTOR, result_card_selector)
529
+ print(f" 代替セレクタで {len(result_cards)} 件発見。")
530
+ if not result_cards:
531
+ print(f" 警告: 代替セレクタ 'a.Nv2PK' で試行...") # さらなる代替
532
+ result_card_selector = 'a.Nv2PK'
533
+ result_cards = list_container_updated.find_elements(By.CSS_SELECTOR, result_card_selector)
534
+ print(f" 代替セレクタで {len(result_cards)} 件発見。")
535
+
536
+ # 取得した要素からリンクURLを抽出
537
+ link_extraction_errors = 0
538
+ for card_idx, card in enumerate(result_cards):
539
+ try:
540
+ link_element = None
541
+ if card.tag_name == 'a': # 要素自体がaタグの場合
542
+ link_element = card
543
+ else: # 要素内にaタグを探す
544
+ try:
545
+ link_element = card.find_element(By.TAG_NAME, 'a')
546
+ except NoSuchElementException:
547
+ continue # aタグがなければスキップ
548
+
549
+ if link_element:
550
+ href = link_element.get_attribute('href')
551
+ # Google Mapsの場所詳細URLか確認
552
+ if href and "/maps/place/" in href and not href.startswith("javascript:"):
553
+ absolute_href = urljoin(base_url, href) # 相対URLを絶対URLに変換
554
+ unique_place_links.add(absolute_href) # setに追加して重複排除
555
+ except StaleElementReferenceException:
556
+ # 要素が古くなった場合は無視して次へ
557
+ link_extraction_errors += 1
558
+ continue
559
+ except Exception as e_extract_link:
560
+ # その他のリンク抽出エラー
561
+ print(f"★★★★★ カード {card_idx+1} からのリンク抽出エラー ★★★★★\n{type(e_extract_link).__name__}: {e_extract_link}")
562
+ link_extraction_errors += 1
563
+ if link_extraction_errors > 0:
564
+ print(f" リンク抽出中に {link_extraction_errors} 件のエラーが発生しました。")
565
+ print(f" 抽出したユニークリンク数: {len(unique_place_links)}")
566
+ except Exception as e_find_links:
567
+ # リンク抽出プロセス全体のエラー
568
+ print(f"★★★★★ リンク抽出プロセス全体でエラー ★★★★★\n使用したセレクタ: '{result_card_selector}'\n{type(e_find_links).__name__}: {e_find_links}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
569
+ results_list.append({'query_index': query_index, 'original_query': query, 'result_rank': 0, 'place_url': driver.current_url, 'html_filename': 'N/A', 'name': f'Error (Link Extraction Fail)', 'url': '', 'phone': 'N/A', 'address': 'N/A', 'reviews': [], 'status': f'Error: Link Extraction Fail'})
570
+ return results_list # リンクがなければ続行不可
571
+
572
+ # 有効なリンクが見つからなかった場合
573
+ if not unique_place_links:
574
+ print(" 有効な詳細ページリンクが見つかりませんでした。このクエリの結果はありません。")
575
+ results_list.append({'query_index': query_index, 'original_query': query, 'result_rank': 0, 'place_url': driver.current_url, 'html_filename': 'N/A', 'name': 'No Results Found', 'url': '', 'phone': 'N/A', 'address': 'N/A', 'reviews': [], 'status': 'Success: No Results'})
576
+ return results_list # 結果がないのでこのクエリは終了
577
+
578
+ # 4. 各リンクの詳細ページを処理
579
+ print(f" {len(unique_place_links)} 件の詳細情報を取得...")
580
+ link_list = sorted(list(unique_place_links))
581
+ processed_urls = set()
582
+
583
+ for i, place_url in enumerate(link_list, 1):
584
+ if place_url in processed_urls: continue # 既に処理済みのURLはスキップ
585
+ processed_urls.add(place_url)
586
+
587
+ print(f"\n --- 詳細取得 [Query:{query_index}, Result:{i}/{len(link_list)}] ---")
588
+ # 結果格納用辞書初期化
589
+ result_details = {'query_index': query_index, 'original_query': query, 'result_rank': i, 'place_url': place_url, 'html_filename': 'N/A', 'name': 'N/A', 'url': '', 'phone': 'N/A', 'address': 'N/A', 'reviews': [], 'status': 'Pending', 'extraction_error': None}
590
+
591
+ try:
592
+ # 詳細ページへ遷移
593
+ print(f" 詳細ページに遷移: {place_url}")
594
+ driver.get(place_url)
595
+ # ページタイトル(h1)が表示されるまで待機
596
+ WebDriverWait(driver, WAIT_TIME_DETAIL).until(
597
+ EC.visibility_of_element_located((By.CSS_SELECTOR, 'h1'))
598
+ )
599
+ time.sleep(WAIT_TIME_BASE * 0.2) # 少し待機
600
+
601
+ # --- 口コミタブをクリック ---
602
+ review_tab_text = "クチコミ" # カタカナ指定
603
+ review_tab_xpath = f"//button[@role='tab'][contains(., '{review_tab_text}') or contains(@aria-label, '{review_tab_text}')]"
604
+ review_tab_clicked = False
605
+ review_scroll_element = None # 口コミスクロール対象要素
606
+ try:
607
+ print(f" {review_tab_text}タブ クリック試行 (XPath: {review_tab_xpath})...")
608
+ # クリック可能になるまで待機
609
+ review_tab = WebDriverWait(driver, 10).until(
610
+ EC.element_to_be_clickable((By.XPATH, review_tab_xpath))
611
+ )
612
+ # スクロールして表示させてからJavaScriptでクリック
613
+ driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", review_tab)
614
+ time.sleep(0.3) # スクロール安定待ち
615
+ driver.execute_script("arguments[0].click();", review_tab)
616
+ review_tab_clicked = True
617
+ print(f" {review_tab_text}タブをクリックしました。口コミコンテナ表示待機...")
618
+
619
+ # --- 口コミコンテナ表示待機 & 要素取得 ---
620
+ review_container_selector = 'div.GHT2ce.NsCY4' # 口コミコンテナのセレクタ
621
+ # コンテナ内の最初のレビューカード(どちらかのクラス)
622
+ first_review_card_selector = f'{review_container_selector} div.jftiEf:first-of-type, {review_container_selector} div.MyEned:first-of-type'
623
+
624
+ # コンテナ要素が表示されるまで待機し、スクロール対象として取得
625
+ review_scroll_element = WebDriverWait(driver, WAIT_TIME_DETAIL).until(
626
+ EC.visibility_of_element_located((By.CSS_SELECTOR, review_container_selector))
627
+ )
628
+ # 念のため、最初のカードも表示されるか短時間待つ
629
+ WebDriverWait(driver, 5).until(
630
+ EC.visibility_of_element_located((By.CSS_SELECTOR, first_review_card_selector))
631
+ )
632
+ print(f" 口コミコンテナ ('{review_container_selector}') 表示確認、スクロール要素取得。")
633
+ time.sleep(WAIT_TIME_BASE * 0.5) # レンダリング待ち
634
+
635
+ except TimeoutException:
636
+ print(f" 警告: {review_tab_text}タブまたは口コミコンテナの表示タイムアウト。")
637
+ except ElementClickInterceptedException:
638
+ print(f" 警告: {review_tab_text}タブのクリックが遮られました。")
639
+ except NoSuchElementException:
640
+ print(f" 警告: {review_tab_text}タブが見つかりません。")
641
+ except Exception as e_click_review:
642
+ # その他のタブクリック関連エラー
643
+ print(f"★★★★★ {review_tab_text}タブ処理中に予期せぬエラー ★★★★★\n{type(e_click_review).__name__}: {e_click_review}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
644
+
645
+ # --- 口コミエリアのスクロール処理 ---
646
+ if review_scroll_element:
647
+ print(" 口コミエリアをスクロールして全件表示試行...")
648
+ review_last_height = driver.execute_script("return arguments[0].scrollHeight", review_scroll_element)
649
+ review_scroll_attempts = 0
650
+ review_stuck_count = 0
651
+ while review_scroll_attempts < MAX_SCROLL_ATTEMPTS_REVIEW:
652
+ try:
653
+ # スクロール実行
654
+ driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', review_scroll_element)
655
+ time.sleep(SCROLL_PAUSE_TIME_REVIEW)
656
+ # 新しい高さを取得
657
+ review_new_height = driver.execute_script("return arguments[0].scrollHeight", review_scroll_element)
658
+
659
+ # 高さが変わらなくなったかチェック
660
+ if review_new_height == review_last_height:
661
+ review_stuck_count += 1
662
+ if review_stuck_count >= REVIEW_SCROLL_STUCK_LIMIT:
663
+ print(f" 口コミスクロール高さが{REVIEW_SCROLL_STUCK_LIMIT}回変化なし。スクロール終了と判断。")
664
+ break
665
+ else:
666
+ # 停滞時は少し長く待って再試行
667
+ time.sleep(SCROLL_PAUSE_TIME_REVIEW * 2)
668
+ else:
669
+ review_stuck_count = 0 # 高さが変わればリセット
670
+
671
+ review_last_height = review_new_height
672
+ except Exception as e_review_scroll:
673
+ # 口コミスクロール中のエラー
674
+ print(f"★★★★★ 口コミスクロール中にエラー ★★★★★\n{type(e_review_scroll).__name__}: {e_review_scroll}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
675
+ print(" 口コミスクロールエラー発生。可能な範囲で続行します。")
676
+ break # スクロールエラー時はループ中断
677
+ review_scroll_attempts += 1
678
+ if review_scroll_attempts >= MAX_SCROLL_ATTEMPTS_REVIEW:
679
+ print(f" 最大口コミスクロール回数 ({MAX_SCROLL_ATTEMPTS_REVIEW}) 到達。")
680
+ print(" 口コミエリアのスクロール完了。")
681
+ elif review_tab_clicked:
682
+ # 口コミタブはクリックできたが、スクロール要素が見つからなかった場合
683
+ print(" 警告: 口コミスクロール要素が見つからなかったため、口コミスクロールをスキップします。")
684
+
685
+
686
+ # --- 「もっと見る」ボタンをクリック ---
687
+ if review_tab_clicked and review_scroll_element: # 口コミタブがクリックされ、スクロール要素が見つかっている場合のみ実行
688
+ print(" 「もっと見る」ボタンを検索してクリック試行...")
689
+ more_buttons_xpath = "//button[contains(text(), 'もっと見る')]" # 「もっと見る」ボタンのXPath (要UI確認)
690
+ clicked_count = 0
691
+ click_attempts = 0
692
+ max_click_attempts = 3 # 複数回試行(動的追加対策)
693
+ while click_attempts < max_click_attempts:
694
+ buttons_found_this_round = 0
695
+ try:
696
+ # 現在表示されている「もっと見る」ボタンを全て取得
697
+ more_buttons = driver.find_elements(By.XPATH, more_buttons_xpath)
698
+ if not more_buttons:
699
+ # ボタンが見つからない場合
700
+ if click_attempts == 0: print(" 「もっと見る」ボタンが見つかりませんでした。")
701
+ else: print(f" 追加の「もっと見る」ボタンは見つかりませんでした (試行 {click_attempts+1}/{max_click_attempts})。")
702
+ break # ループ終了
703
+
704
+ print(f" 「もっと見る」ボタンを {len(more_buttons)} 個発見 (試行 {click_attempts+1}/{max_click_attempts})。クリック開始...")
705
+ # 見つかったボタンを順番にクリック
706
+ for btn_idx, button in enumerate(more_buttons):
707
+ try:
708
+ # ボタンが表示されていてクリック可能か確認
709
+ if button.is_displayed() and button.is_enabled():
710
+ # JavaScriptでクリック (クリック妨害対策)
711
+ driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) # ボタンを画面中央へ
712
+ time.sleep(0.2) # スクロール待機
713
+ driver.execute_script("arguments[0].click();", button)
714
+ clicked_count += 1
715
+ buttons_found_this_round += 1
716
+ time.sleep(0.3) # クリック後のDOM変化/読み込み待ち
717
+ except ElementClickInterceptedException:
718
+ # クリックが遮られた場合
719
+ print(f" ボタン {btn_idx+1} のクリックが遮られました。スキップします。")
720
+ except StaleElementReferenceException:
721
+ # 要素が古くなった場合
722
+ print(f" ボタン {btn_idx+1} が古くなりました。スキップします。")
723
+ except Exception as e_click_more:
724
+ # その他のクリックエラー
725
+ print(f" ボタン {btn_idx+1} のクリック中に���ラー: {e_click_more}")
726
+ print(f" 今回の試行で {buttons_found_this_round} 個の「もっと見る」ボタンをクリックしました。")
727
+ # 今回クリックできるボタンがなければ終了
728
+ if buttons_found_this_round == 0:
729
+ print(" これ以上クリックできる「もっと見る」ボタンはありませんでした。")
730
+ break
731
+
732
+ except Exception as e_find_more:
733
+ # 「もっと見る」ボタン検索中のエラー
734
+ print(f"★★★★★ 「もっと見る」ボタン検索中にエラー ★★★★★\n{type(e_find_more).__name__}: {e_find_more}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
735
+ break # 検索エラー時はループ終了
736
+ click_attempts += 1
737
+ # 次の検索まで少し待つ (DOM更新待ち)
738
+ if click_attempts < max_click_attempts:
739
+ time.sleep(1.0)
740
+
741
+ # クリック結果のサマリー
742
+ if clicked_count > 0:
743
+ print(f" 合計 {clicked_count} 個の「もっと見る」ボタンをクリックしました。")
744
+ else:
745
+ print(" クリックされた「もっと見る」ボタンはありませんでした。")
746
+ # 全てのクリック処理後に少し待つ
747
+ time.sleep(WAIT_TIME_BASE * 0.5)
748
+
749
+ # --- HTML取得と保存 (「もっと見る」クリック後) ---
750
+ print(" ページのHTMLを取得・保存中...")
751
+ detail_html_content = ""
752
+ try:
753
+ # 全ての操作が終わった後のHTMLを取得
754
+ detail_html_content = driver.page_source
755
+ # ファイル名生成
756
+ temp_name = 'N/A'
757
+ try: temp_name = driver.find_element(By.TAG_NAME, 'h1').text
758
+ except: pass # h1が見つからなくてもエラーにしない
759
+ safe_place_name_part = re.sub(r'[\\/*?:"<>|]', '_', temp_name)[:20].strip() or "no_name"
760
+ tab_suffix = "_reviews_expanded" if review_tab_clicked else "_overview" # ファイル名で状態を示す
761
+ detail_html_fname = f"Q{query_index:03d}_R{i:03d}_{safe_place_name_part}_{safe_query_part}_detail{tab_suffix}.html"
762
+ detail_html_path = os.path.join(output_dir, detail_html_fname)
763
+ # ファイル書き込み
764
+ with open(detail_html_path, 'w', encoding='utf-8') as f:
765
+ f.write(detail_html_content)
766
+ result_details['html_filename'] = detail_html_fname
767
+ print(f" HTMLを保存しました: {detail_html_fname}")
768
+ except Exception as e_save_html:
769
+ # HTML保存エラー
770
+ print(f" HTML取得/保存エラー: {e_save_html}")
771
+ result_details['html_filename'] = 'Error Saving HTML'
772
+
773
+ # --- HTML解析 (本文抽出ロジックは関数側で変更済み) ---
774
+ if detail_html_content:
775
+ print(" HTMLを解析して情報を抽出中...")
776
+ extracted_info = extract_details_and_reviews_from_html(detail_html_content)
777
+ # 抽出結果をマージ
778
+ result_details.update(extracted_info)
779
+ # ステータス設定
780
+ if result_details.get('extraction_error'):
781
+ result_details['status'] = f"Warning: HTML Extraction Error" # 抽出エラーは警告
782
+ else:
783
+ result_details['status'] = 'Success'
784
+ print(" HTML解析完了。")
785
+ else:
786
+ # HTMLが取得できなかった場合
787
+ print(" エラー: HTMLコンテンツが空のため、情報抽出をスキップします。")
788
+ result_details['status'] = 'Error: Empty HTML Content'
789
+
790
+ # 詳細ページ処理中の各種例外ハンドリング
791
+ except TimeoutException as e_timeout_detail:
792
+ print(f"★★★★★ 詳細ページ読み込みタイムアウト ★★★★★\nURL: {place_url}\n{e_timeout_detail}")
793
+ # ★★★ SyntaxError修正 ★★★
794
+ print("--- HTML Snapshot (Timeout) ---")
795
+ try:
796
+ print(driver.page_source[:1000])
797
+ except Exception as e_snapshot:
798
+ print(f" ページソース取得失敗: {e_snapshot}")
799
+ print("--- End Snapshot ---")
800
+ result_details['status'] = f'Error: Detail Page Timeout'; result_details['name'] = f"Error (Timeout R:{i})"
801
+ except NoSuchElementException as e_nse:
802
+ # 主にh1が見つからないケースなど
803
+ print(f"★★★★★ 詳細ページで必須要素(h1など)が見つかりません ★★★★★\nURL: {place_url}\n{e_nse}")
804
+ # ★★★ SyntaxError修正 ★★★
805
+ print("--- HTML Snapshot (NSE) ---")
806
+ try:
807
+ print(driver.page_source[:1000])
808
+ except Exception as e_snapshot:
809
+ print(f" ページソース取得失敗: {e_snapshot}")
810
+ print("--- End Snapshot ---")
811
+ result_details['status'] = f'Error: Detail Page Missing Element (e.g., h1)'; result_details['name'] = f"Error (ElementNotFound R:{i})"
812
+ except Exception as e_detail:
813
+ # その他の予期せぬエラー
814
+ print(f"★★★★★ 詳細ページ処理中に予期せぬエラー ★★★★★\nURL: {place_url}\n{type(e_detail).__name__}: {e_detail}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
815
+ result_details['status'] = f'Error: Detail Page Exception - {type(e_detail).__name__}'; result_details['name'] = f"Error (Exception R:{i})"
816
+ finally:
817
+ # 処理結果をリストに追加
818
+ results_list.append(result_details)
819
+
820
+ except Exception as e_main_query:
821
+ # クエリ単位での大きなエラー
822
+ print(f"★★★★★ クエリ '{query}' [Index:{query_index}] の処理全体でエラー ★★★★★\n{type(e_main_query).__name__}: {e_main_query}\n--- Traceback ---\n{traceback.format_exc()}\n--- End Traceback ---")
823
+ results_list.append({'query_index': query_index, 'original_query': query, 'result_rank': 0, 'place_url': 'N/A', 'html_filename': 'N/A', 'name': f'Error (Overall Query {query_index})', 'url': '', 'phone': 'N/A', 'address': 'N/A', 'reviews': [], 'status': f'Error: Query Level Exception - {type(e_main_query).__name__}'})
824
+ finally:
825
+ # クエリ処理終了ログ
826
+ print(f"--- クエリ処理終了 [Index:{query_index}] - {len(results_list)} 件の結果 ---")
827
+ return results_list
828
+
829
+
830
+ # --- Gradio Processing Function ---
831
+ def run_scraping(input_csv_file, output_dir_name, output_csv_name, csv_encoding,
832
+ wait_time_base, wait_time_detail, wait_time_search, headless_mode):
833
+ """Gradioインターフェースから呼び出されるメイン処理関数"""
834
+ log_stream = io.StringIO() # ログ出力用
835
+ start_time_total = time.time() # 全体処理時間計測開始
836
+ driver = None # WebDriverオブジェクト初期化
837
+ processed_query_count = 0 # 処理済みクエリ数
838
+ total_results_count = 0 # CSV書き込み総行数
839
+ total_queries = 0 # 総クエリ数
840
+ output_csv_path = None # 出力CSVファイルパス
841
+
842
+ # 標準出力と標準エラー出力をログストリームにリダイレクト
843
+ with contextlib.redirect_stdout(log_stream), contextlib.redirect_stderr(log_stream):
844
+ try:
845
+ print("=== 処理開始 ===")
846
+ print(f"開始時刻: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
847
+ # 入力ファイルチェック
848
+ if input_csv_file is None:
849
+ print("エラー: CSVファイルが選択されていません。処理を中断します。")
850
+ yield log_stream.getvalue(), None # ログと空の結果を返す
851
+ return
852
+ yield log_stream.getvalue(), None # 初期ログをUIに反映
853
+
854
+ # パラメータ設定
855
+ SEARCH_QUERIES_CSV_PATH = input_csv_file.name
856
+ OUTPUT_DIR = output_dir_name.strip() or "html_reviews_expanded" # HTML保存ディレクトリ
857
+ OUTPUT_CSV_FILENAME = output_csv_name.strip() or "結果_reviews_expanded.csv" # 出力CSV名
858
+ CSV_ENCODING = csv_encoding # CSVエンコーディング
859
+ # 待機時間設定 (不正値チェック含む)
860
+ try:
861
+ wait_config = {
862
+ 'base': max(1.0, float(wait_time_base)),
863
+ 'detail': max(10.0, float(wait_time_detail)),
864
+ 'search': max(5.0, float(wait_time_search))
865
+ }
866
+ except ValueError:
867
+ print("警告: 待機時間に無効な値が入力されました。デフォルト値を使用します。")
868
+ wait_config = {'base': 4.0, 'detail': 20.0, 'search': 15.0}
869
+ print(f"待機時間設定: 基本={wait_config['base']}秒, 詳細/口コミ={wait_config['detail']}秒, 検索={wait_config['search']}秒")
870
+ yield log_stream.getvalue(), None
871
+
872
+ # 出力ディレクトリ設定と作成
873
+ if not os.path.isabs(OUTPUT_DIR): # 相対パスなら絶対パスに変換
874
+ OUTPUT_DIR = os.path.join(os.getcwd(), OUTPUT_DIR)
875
+ output_csv_path = os.path.join(OUTPUT_DIR, OUTPUT_CSV_FILENAME)
876
+ print(f"HTML出力先ディレクトリ: {OUTPUT_DIR}")
877
+ print(f"CSV出力先ファイル: {output_csv_path}")
878
+ os.makedirs(OUTPUT_DIR, exist_ok=True) # ディレクトリが存在しなければ作成
879
+ yield log_stream.getvalue(), None
880
+
881
+ # CSVからクエリ読み込み
882
+ queries = load_queries(SEARCH_QUERIES_CSV_PATH)
883
+ yield log_stream.getvalue(), None # ログ更新
884
+ if not queries:
885
+ print("エラー: CSVから処理可能なクエリが見つかりませんでした。処理を終了します。")
886
+ yield log_stream.getvalue(), None
887
+ return
888
+ total_queries = len(queries)
889
+ print(f"{total_queries} 件のクエリを処理します。")
890
+ yield log_stream.getvalue(), None
891
+
892
+ # WebDriver初期化
893
+ print("\nWebDriver初期化中...")
894
+ yield log_stream.getvalue(), None
895
+ options = Options()
896
+ options.add_argument('--no-sandbox')
897
+ options.add_argument('--disable-dev-shm-usage')
898
+ options.add_argument('--lang=ja-JP') # 日本語指定
899
+ options.add_argument("--window-size=1920,1080") # ウィンドウサイズ
900
+ options.add_argument('--disable-extensions') # 拡張機能無効化
901
+ options.add_argument('--disable-blink-features=AutomationControlled') # 自動化検出回避策
902
+ options.add_argument('--disable-gpu') # GPU無効化(安定性向上目的)
903
+ # 自動化フラグを隠すオプション
904
+ options.add_experimental_option('excludeSwitches', ['enable-automation'])
905
+ options.add_experimental_option('useAutomationExtension', False)
906
+ # パスワード保存ダイアログなどを無効化
907
+ options.add_experimental_option("prefs", {
908
+ "credentials_enable_service": False,
909
+ "profile.password_manager_enabled": False
910
+ })
911
+ # ヘッドレスモード設定
912
+ if headless_mode:
913
+ print(" ヘッドレスモードで実行します。")
914
+ options.add_argument('--headless=new') # 新しいヘッドレスモード
915
+ else:
916
+ print(" 通常モード (非ヘッドレス) で実行します。")
917
+
918
+ # WebDriverインスタンス生成
919
+ try:
920
+ if IN_COLAB and gs:
921
+ # Colab環境
922
+ print(" Colab環境でgoogle_colab_seleniumを使用します。")
923
+ driver = gs.Chrome(options=options)
924
+ elif not IN_COLAB and ChromeService and ChromeDriverManager:
925
+ # ローカル環境 (webdriver-manager使用)
926
+ try:
927
+ print(" webdriver-managerを使用してChromeDriverパスを解決します...")
928
+ service = ChromeService(ChromeDriverManager().install())
929
+ driver = webdriver.Chrome(service=service, options=options)
930
+ print(" ChromeDriver (webdriver-manager) 起動成功。")
931
+ except Exception as e_wdm:
932
+ # webdriver-manager失敗時のフォールバック
933
+ print(f" webdriver-managerでの初期化エラー: {e_wdm}")
934
+ print(" PATH上のChromeDriverで試行します...")
935
+ driver = webdriver.Chrome(options=options) # PATH上のドライバで再試行
936
+ print(" ChromeDriver (PATH) 起動成功。")
937
+ elif not IN_COLAB:
938
+ # ローカル環境 (webdriver-managerなし、PATH上のドライバ使用)
939
+ print(" PATH上のChromeDriverを使用します...")
940
+ driver = webdriver.Chrome(options=options)
941
+ print(" ChromeDriver (PATH) 起動成功。")
942
+ else:
943
+ # 上記いずれでもない場合 (通常は発生しない)
944
+ raise Exception("WebDriverを初期化できませんでした。適切なWebDriver設定が見つかりません。")
945
+
946
+ # 暗黙的な待機 (要素が見つかるまで指定秒数待つ)
947
+ driver.implicitly_wait(3)
948
+ print("WebDriver初期化完了。")
949
+ except Exception as e_wd_init:
950
+ # WebDriver初期化失敗時のエラー処理
951
+ print(f"★★★★★ WebDriver初期化失敗 ★★★★★")
952
+ print(f"エラータイプ: {type(e_wd_init).__name__}")
953
+ print(f"エラーメッセージ: {e_wd_init}")
954
+ print("--- スタックトレース ---")
955
+ print(traceback.format_exc())
956
+ print("----------------------")
957
+ print("ヒント: ChromeDriverのバージョンとChromeブラウザのバージョンが一致しているか確認してください。")
958
+ if not IN_COLAB: print(" `webdriver-manager`がインストールされていない場合は `pip install webdriver-manager` を試してください。")
959
+ yield log_stream.getvalue(), None # ログと空の結果を返す
960
+ return # WebDriverがないと処理継続不可
961
+ yield log_stream.getvalue(), None
962
+
963
+ # CSVヘッダー定義 (「もっと見る」クリック版)
964
+ csv_header = ['QueryIndex', 'OriginalQuery', 'ResultRank', 'Status', 'ExtractedName',
965
+ 'ExtractedWebsite', 'ExtractedPhone', 'ExtractedAddress', 'Reviews', # 口コミ列
966
+ 'ExtractionError', # HTML抽出エラー列
967
+ 'PlaceURL', 'DetailHTMLFilename']
968
+ # CSVファイルモード設定 (追記 'a' or 新規 'w')
969
+ file_exists = os.path.exists(output_csv_path)
970
+ file_mode = 'a' if file_exists and os.path.getsize(output_csv_path) > 0 else 'w'
971
+ print(f"CSVファイルを '{file_mode}' モードで開きます (エンコーディング: {CSV_ENCODING})。")
972
+ yield log_stream.getvalue(), None
973
+
974
+ # CSVファイル処理 (メインループ)
975
+ try:
976
+ # CSVファイルを指定モード・エンコーディングで開く
977
+ with open(output_csv_path, file_mode, newline='', encoding=CSV_ENCODING, errors='replace') as csv_file:
978
+ writer = csv.writer(csv_file)
979
+ # 新規ファイルの場合、ヘッダー行を書き込む
980
+ if file_mode == 'w':
981
+ print(" 新規CSVファイルのためヘッダー行を書き込みます。")
982
+ writer.writerow(csv_header)
983
+ csv_file.flush() # ヘッダー書き込み後すぐにフラッシュ
984
+ elif file_exists:
985
+ print(f" 既存ファイル '{os.path.basename(output_csv_path)}' に追記します。")
986
+
987
+ # クエリごとに処理を実行
988
+ for i, query in enumerate(queries, 1):
989
+ start_time_query = time.time() # クエリ処理時間計測開始
990
+ print(f"\n===== クエリ {i}/{total_queries} 開始: '{query}' =====")
991
+ yield log_stream.getvalue(), None # 各クエリ開始前にログ更新
992
+
993
+ # --- 単一クエリのスクレイピング処理実行 ---
994
+ results = process_single_query_full_list(driver, query, i, OUTPUT_DIR, wait_config)
995
+ yield log_stream.getvalue(), None # クエリ処理後にログ更新
996
+
997
+ # --- 取得結果をCSVに書き込み ---
998
+ written_count_query = 0
999
+ print(f" クエリ {i} の結果をCSVに書き込み中...")
1000
+ for result_data in results:
1001
+ try:
1002
+ # レビューデータを整形して文字列にする
1003
+ reviews_list = result_data.get('reviews', [])
1004
+ formatted_reviews = ""
1005
+ if isinstance(reviews_list, list) and reviews_list:
1006
+ review_texts = []
1007
+ for idx, review_item in enumerate(reviews_list):
1008
+ # 各レビューをフォーマット
1009
+ if isinstance(review_item, dict):
1010
+ r_text = str(review_item.get('text', '')).replace('\n', ' ').replace('\r', '') # 改行をスペースに
1011
+ review_texts.append(
1012
+ f"[{idx+1}] 投稿者: {review_item.get('reviewer', 'N/A')} | "
1013
+ f"評価: {review_item.get('rating', 'N/A')} | "
1014
+ f"本文: {r_text}"
1015
+ )
1016
+ elif isinstance(review_item, str): # 予期せぬ形式の場合
1017
+ review_texts.append(f"[{idx+1}] {review_item.replace('n', ' ').replace('r', '')}")
1018
+ # 各レビューを改行2つで結合
1019
+ formatted_reviews = "\n\n".join(review_texts)
1020
+ elif isinstance(reviews_list, str): # 既に文字列の場合
1021
+ formatted_reviews = reviews_list.replace('\n', ' ').replace('\r', '')
1022
+
1023
+ # HTML抽出エラーメッセージを取得 (長すぎる場合は短縮)
1024
+ extraction_error_msg = result_data.get('extraction_error', '')
1025
+ if extraction_error_msg and len(extraction_error_msg) > 500:
1026
+ extraction_error_msg = extraction_error_msg[:250] + "..." + extraction_error_msg[-250:]
1027
+
1028
+ # CSVに書き込む行データを作成 (ヘッダー順に合わせる)
1029
+ row_data = [
1030
+ result_data.get('query_index', i),
1031
+ result_data.get('original_query', query),
1032
+ result_data.get('result_rank', 'N/A'),
1033
+ result_data.get('status', 'Unknown'),
1034
+ result_data.get('name', 'N/A'),
1035
+ result_data.get('url', ''),
1036
+ result_data.get('phone', 'N/A'),
1037
+ result_data.get('address', 'N/A'),
1038
+ formatted_reviews, # 整形済みレビュー
1039
+ extraction_error_msg, # HTML抽出エラー
1040
+ result_data.get('place_url', 'N/A'),
1041
+ result_data.get('html_filename', 'N/A')
1042
+ ]
1043
+ # CSVファイルに書き込み
1044
+ writer.writerow(row_data)
1045
+ written_count_query += 1
1046
+ except Exception as e_write:
1047
+ # CSV書き込み中のエラー処理
1048
+ print(f"★★★★★ CSV書き込み中にエラーが発生しました (行スキップ) ★★★★★")
1049
+ print(f"エラーデータ (一部): {str(result_data)[:200]}...") # エラー原因データを一部表示
1050
+ print(f"エラータイプ: {type(e_write).__name__}: {e_write}")
1051
+
1052
+ csv_file.flush() # 各クエリ処理後にファイルに書き出す
1053
+ total_results_count += written_count_query
1054
+ processed_query_count += 1
1055
+ end_time_query = time.time() # クエリ処理時間計測終了
1056
+ print(f"===== クエリ {i}/{total_queries} 完了 - {written_count_query}件書き込み, 所要時間: {end_time_query - start_time_query:.2f} 秒 =====")
1057
+ yield log_stream.getvalue(), None # 各クエリ完了後にログ更新
1058
+
1059
+ # --- クエリ間の待機 ---
1060
+ if i < total_queries: # 最後のクエリの後には待機しない
1061
+ # ランダム性を持たせた待機時間
1062
+ sleep_duration = wait_config['base'] * 1.5 + (hash(query + str(i)) % (wait_config['base'] * 1.5))
1063
+ sleep_duration = max(wait_config['base'] * 0.8, min(sleep_duration, wait_config['base'] * 4.0))
1064
+ print(f"次のクエリまで {sleep_duration:.2f} 秒待機します...")
1065
+ yield log_stream.getvalue(), None
1066
+ time.sleep(sleep_duration)
1067
+ else:
1068
+ print("\n全クエリの処理が完了しました。")
1069
+
1070
+ except IOError as e_io:
1071
+ # CSVファイルオープン/書き込み時のIOエラー
1072
+ print(f"★★★★★ CSVファイル '{output_csv_path}' のオープン/書き込み中にIOエラー ★★★★★")
1073
+ print(f"エラータイプ: {type(e_io).__name__}")
1074
+ print(f"エラーメッセージ: {e_io}")
1075
+ print("--- スタックトレース ---")
1076
+ print(traceback.format_exc())
1077
+ print("----------------------")
1078
+ print("ファイルが他のプログラムで開かれていないか、書き込み権限があるか確認してください。")
1079
+ output_csv_path = None # 結果ファイルパスを無効化
1080
+ except Exception as e_csv_loop:
1081
+ # CSV処理ループ中の予期せぬエラー
1082
+ print(f"★★★★★ CSV処理ループ中に予期せぬエラー ★★★★★")
1083
+ print(f"エラータイプ: {type(e_csv_loop).__name__}")
1084
+ print(f"エラーメッセージ: {e_csv_loop}")
1085
+ print("--- スタックトレース ---")
1086
+ print(traceback.format_exc())
1087
+ print("----------------------")
1088
+
1089
+
1090
+ except Exception as e_main:
1091
+ # run_scraping関数全体での予期せぬエラー
1092
+ print(f"\n★★★★★ メイン処理 (run_scraping) 中に予期せぬエラーが発生しました ★★★★★")
1093
+ print(f"エラータイプ: {type(e_main).__name__}")
1094
+ print(f"エラーメッセージ: {e_main}")
1095
+ print("\n--- スタックトレース ---")
1096
+ print(traceback.format_exc()) # スタックトレースをログに出力
1097
+ print("----------------------")
1098
+ # エラー発生時も、可能な限りログと途中までのCSVを返す
1099
+ yield log_stream.getvalue(), output_csv_path if output_csv_path and os.path.exists(output_csv_path) else None
1100
+ return # 処理終了
1101
+
1102
+ finally:
1103
+ # --- 終了処理 ---
1104
+ if driver:
1105
+ print("\nWebDriver終了処理中...")
1106
+ try:
1107
+ driver.quit() # ブラウザを閉じる
1108
+ print("WebDriver正常終了。")
1109
+ except Exception as e_quit:
1110
+ # WebDriver終了時のエラー
1111
+ print(f"★★★★★ WebDriver終了時にエラー ★★★★★")
1112
+ print(f"エラータイプ: {type(e_quit).__name__}: {e_quit}")
1113
+
1114
+ # 全体処理時間計測終了と結果表示
1115
+ end_time_total = time.time()
1116
+ total_duration_seconds = end_time_total - start_time_total
1117
+ print(f"\n=== 全処理終了 ===")
1118
+ print(f"終了時刻: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
1119
+ print(f"処理完了クエリ数: {processed_query_count}/{total_queries if total_queries > 0 else 'N/A'} 件")
1120
+ print(f"CSV書き込み総行数: {total_results_count} 件")
1121
+ print(f"総処理時間: {total_duration_seconds:.2f} 秒 ({total_duration_seconds/60:.2f} 分)")
1122
+
1123
+ # 最終ログを取得
1124
+ final_log = log_stream.getvalue()
1125
+
1126
+ # 結果CSVファイルの存在確認とGradioへの出力設定
1127
+ if output_csv_path and os.path.exists(output_csv_path) and os.path.getsize(output_csv_path) > 0:
1128
+ print(f"結果CSVファイル: {output_csv_path}")
1129
+ # GradioのFileコンポーネントにファイルパスを渡してダウンロード可能にする
1130
+ yield final_log, gr.File(value=output_csv_path, label="結果CSVダウンロード")
1131
+ elif output_csv_path:
1132
+ # ファイルパスはあるが、空か存在しない場合
1133
+ print(f"警告: 結果CSVファイル '{output_csv_path}' は空または存在しません。")
1134
+ yield final_log, None
1135
+ else:
1136
+ # ファイルパス自体がない場合 (IOErrorなど)
1137
+ print("結果CSVファイルは生成されませんでした。")
1138
+ yield final_log, None
1139
+
1140
+
1141
+ # --- Gradio UI 定義 ---
1142
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1143
+ gr.Markdown("# Google Maps スクレイピング (口コミ全件表示試行)") # タイトル
1144
+ gr.Markdown(
1145
+ """
1146
+ CSVクエリで検索し、詳細ページで「クチコミ」タブをクリック後、口コミエリアを**最後までスクロール**し、
1147
+ さらに**「もっと見る」ボタンを全てクリック**して全件表示を試みます。
1148
+ その後、基本情報と口コミ情報(`span.wiI7pd`優先)を抽出し、CSVに出力します。
1149
+ **処理フロー:**
1150
+ 1. クエリ検索 → リストスクロール → リンク抽出。
1151
+ 2. 詳細ページ遷移 → **「クチコミ」タブクリック** → 口コミコンテナ待機。
1152
+ 3. **口コミエリアを最後までスクロール**。
1153
+ 4. **「もっと見る」ボタンを全てクリック** (複数回試行)。
1154
+ 5. HTML取得 → **bs4**で解析 (基本情報: `.aIFcqe`優先, 口コミ本文: `span.wiI7pd`優先)。
1155
+ 6. 結果をCSVに出力(HTMLも保存)。
1156
+
1157
+ **注意:** 「もっと見る」ボタンの挙動やセレクタは変わりやすいです。エラーログを確認し、コード修正が必要になる場合があります。
1158
+ """
1159
+ ) # 説明文
1160
+
1161
+ with gr.Row():
1162
+ with gr.Column(scale=2):
1163
+ gr.Markdown("### ① 入力ファイルと出力設定")
1164
+ input_csv_file = gr.File(label="検索クエリCSVファイル (1列目のみ使用)", file_types=[".csv"])
1165
+ output_dir_name = gr.Textbox(label="HTML保存先ディレクトリ名", value="html_reviews_expanded")
1166
+ output_csv_name = gr.Textbox(label="出力CSVファイル名", value="結果_reviews_expanded.csv")
1167
+ csv_encoding = gr.Dropdown(label="出力CSVエンコーディング", choices=['utf-8-sig', 'cp932'], value='utf-8-sig')
1168
+ headless_mode = gr.Checkbox(label="ヘッドレスモードで実行 (エラー発生時はOFF推奨)", value=True)
1169
+ with gr.Column(scale=1):
1170
+ gr.Markdown("### ② 待機時間設定 (秒)")
1171
+ wait_time_base = gr.Number(label="基本待機", minimum=1, maximum=20, step=0.5, value=4)
1172
+ wait_time_detail = gr.Number(label="詳細/口コミ最大待機", minimum=10, maximum=60, step=1, value=25)
1173
+ wait_time_search = gr.Number(label="検索リスト最大待機", minimum=5, maximum=60, step=1, value=15)
1174
+
1175
+ start_button = gr.Button("処理開始", variant="primary", size="lg")
1176
+ gr.Markdown("### ③ 処理ステータスとエラーログ")
1177
+ # ログ表示エリアの設定 (行数、スクロール)
1178
+ status_textbox = gr.Textbox(label="ログ", lines=25, interactive=False, autoscroll=True, max_lines=2000)
1179
+ gr.Markdown("### ④ 結果ダウンロード")
1180
+ # 結果ファイルダウンロード用コンポーネント
1181
+ output_csv_download = gr.File(label="結果CSVダウンロード", interactive=False)
1182
+
1183
+ # ボタンクリック時の動作設定
1184
+ start_button.click(
1185
+ fn=run_scraping, # 実行する関数
1186
+ inputs=[input_csv_file, output_dir_name, output_csv_name, csv_encoding,
1187
+ wait_time_base, wait_time_detail, wait_time_search, headless_mode], # 入力コンポーネント
1188
+ outputs=[status_textbox, output_csv_download] # 出力コンポーネント
1189
+ )
1190
+
1191
+ # --- UI起動 ---
1192
+ print("Gradio UIを起動します...")
1193
+ # queue()で複数ユーザー対応、share=IN_COLABでColab環境なら共有リンク生成
1194
+ demo.queue().launch(share=IN_COLAB, debug=False)