• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kimata / my-py-lib / 20676727177

03 Jan 2026 11:35AM UTC coverage: 64.965% (+0.007%) from 64.958%
20676727177

push

github

kimata
chore: tests/fixtures/ を git 追跡対象に変更

テストフィクスチャをリポジトリに含めるため除外設定を削除

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

3169 of 4878 relevant lines covered (64.97%)

0.65 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

40.57
/src/my_lib/selenium_util.py
1
#!/usr/bin/env python3
2
"""
3
Selenium を Chrome Driver を使って動かします。
4

5
Usage:
6
  selenium_util.py [-c CONFIG] [-D]
7

8
Options:
9
  -c CONFIG         : CONFIG を設定ファイルとして読み込んで実行します。
10
                      [default: tests/fixtures/config.example.yaml]
11
  -D                : デバッグモードで動作します。
12
"""
13

14
from __future__ import annotations
1✔
15

16
import datetime
1✔
17
import inspect
1✔
18
import io
1✔
19
import json
1✔
20
import logging
1✔
21
import os
1✔
22
import pathlib
1✔
23
import random
1✔
24
import re
1✔
25
import shutil
1✔
26
import signal
1✔
27
import sqlite3
1✔
28
import subprocess
1✔
29
import time
1✔
30
from dataclasses import dataclass
1✔
31
from typing import TYPE_CHECKING, Any, Self, TypeVar
1✔
32

33
import PIL.Image
1✔
34
import psutil
1✔
35
import selenium
1✔
36
import selenium.common.exceptions
1✔
37
import selenium.webdriver.chrome.options
1✔
38
import selenium.webdriver.chrome.service
1✔
39
import selenium.webdriver.common.action_chains
1✔
40
import selenium.webdriver.common.by
1✔
41
import selenium.webdriver.common.keys
1✔
42
import selenium.webdriver.support.expected_conditions
1✔
43
import undetected_chromedriver
1✔
44

45
import my_lib.time
1✔
46

47
if TYPE_CHECKING:
48
    import types
49
    from collections.abc import Callable
50

51
    from selenium.webdriver.remote.webdriver import WebDriver
52
    from selenium.webdriver.support.wait import WebDriverWait
53

54
T = TypeVar("T")
1✔
55

56
WAIT_RETRY_COUNT: int = 1
1✔
57

58

59
class SeleniumError(Exception):
1✔
60
    """Selenium 関連エラーの基底クラス"""
61

62

63
def _get_chrome_version() -> int | None:
1✔
64
    try:
1✔
65
        result = subprocess.run(
1✔
66
            ["google-chrome", "--version"],  # noqa: S607
67
            capture_output=True,
68
            text=True,
69
            timeout=10,
70
            check=False,
71
        )
72
        match = re.search(r"(\d+)\.", result.stdout)
1✔
73
        if match:
1✔
74
            return int(match.group(1))
1✔
75
    except Exception:
1✔
76
        logging.warning("Failed to detect Chrome version")
1✔
77
    return None
1✔
78

79

80
def _create_driver_impl(
1✔
81
    profile_name: str,
82
    data_path: pathlib.Path,
83
    is_headless: bool,  # noqa: FBT001
84
    use_subprocess: bool = True,  # noqa: FBT001
85
) -> WebDriver:
86
    chrome_data_path = data_path / "chrome"
×
87
    log_path = data_path / "log"
×
88

89
    # NOTE: Pytest を並列実行できるようにする
90
    suffix = os.environ.get("PYTEST_XDIST_WORKER", None)
×
91
    if suffix is not None:
×
92
        profile_name += "." + suffix
×
93

94
    chrome_data_path.mkdir(parents=True, exist_ok=True)
×
95
    log_path.mkdir(parents=True, exist_ok=True)
×
96

97
    options = selenium.webdriver.chrome.options.Options()
×
98

99
    if is_headless:
×
100
        options.add_argument("--headless=new")
×
101

102
    options.add_argument("--no-sandbox")  # for Docker
×
103
    options.add_argument("--disable-dev-shm-usage")  # for Docker
×
104
    options.add_argument("--disable-gpu")
×
105

106
    options.add_argument("--disable-popup-blocking")
×
107
    options.add_argument("--disable-plugins")
×
108

109
    options.add_argument("--no-first-run")
×
110

111
    options.add_argument("--lang=ja-JP")
×
112
    options.add_argument("--window-size=1920,1080")
×
113

114
    # NOTE: Accept-Language ヘッダーを日本語優先に設定
115
    options.add_experimental_option("prefs", {"intl.accept_languages": "ja-JP,ja,en-US,en"})
×
116

117
    options.add_argument("--user-data-dir=" + str(chrome_data_path / profile_name))
×
118

119
    options.add_argument("--enable-logging")
×
120
    options.add_argument("--v=1")
×
121

122
    chrome_log_file = log_path / f"chrome_{profile_name}.log"
×
123
    options.add_argument(f"--log-file={chrome_log_file!s}")
×
124

125
    if not is_headless:
×
126
        options.add_argument("--auto-open-devtools-for-tabs")
×
127

128
    service = selenium.webdriver.chrome.service.Service(
×
129
        service_args=["--verbose", f"--log-path={str(log_path / 'webdriver.log')!s}"],
130
    )
131

132
    chrome_version = _get_chrome_version()
×
133

134
    # NOTE: user_multi_procs=True は既存の chromedriver ファイルが存在することを前提としているため、
135
    # ファイルが存在しない場合(CI環境の初回実行など)は False にする
136
    uc_data_path = pathlib.Path("~/.local/share/undetected_chromedriver").expanduser()
×
137
    use_multi_procs = uc_data_path.exists() and any(uc_data_path.glob("*chromedriver*"))
×
138

139
    driver = undetected_chromedriver.Chrome(
×
140
        service=service,
141
        options=options,
142
        use_subprocess=use_subprocess,
143
        version_main=chrome_version,
144
        user_multi_procs=use_multi_procs,
145
    )
146

147
    driver.set_page_load_timeout(30)
×
148

149
    # CDP を使って日本語ロケールを強制設定
150
    set_japanese_locale(driver)
×
151

152
    return driver
×
153

154

155
@dataclass
1✔
156
class _ProfileHealthResult:
1✔
157
    """プロファイル健全性チェックの結果"""
158

159
    is_healthy: bool
1✔
160
    errors: list[str]
1✔
161
    has_lock_files: bool = False
1✔
162
    has_corrupted_json: bool = False
1✔
163
    has_corrupted_db: bool = False
1✔
164

165

166
def _check_json_file(file_path: pathlib.Path) -> str | None:
1✔
167
    """JSON ファイルの整合性をチェック
168

169
    Returns:
170
        エラーメッセージ(正常な場合は None)
171

172
    """
173
    if not file_path.exists():
1✔
174
        return None
1✔
175

176
    try:
1✔
177
        content = file_path.read_text(encoding="utf-8")
1✔
178
        json.loads(content)
1✔
179
        return None
1✔
180
    except json.JSONDecodeError as e:
1✔
181
        return f"{file_path.name} is corrupted: {e}"
1✔
182
    except Exception as e:
×
183
        return f"{file_path.name} read error: {e}"
×
184

185

186
def _check_sqlite_db(db_path: pathlib.Path) -> str | None:
1✔
187
    """SQLite データベースの整合性をチェック
188

189
    Returns:
190
        エラーメッセージ(正常な場合は None)
191

192
    """
193
    if not db_path.exists():
1✔
194
        return None
1✔
195

196
    try:
1✔
197
        conn = sqlite3.connect(str(db_path), timeout=5)
1✔
198
        result = conn.execute("PRAGMA integrity_check").fetchone()
1✔
199
        conn.close()
1✔
200
        if result[0] != "ok":
1✔
201
            return f"{db_path.name} database is corrupted: {result[0]}"
×
202
        return None
1✔
203
    except sqlite3.DatabaseError as e:
1✔
204
        return f"{db_path.name} database error: {e}"
1✔
205
    except Exception as e:
×
206
        return f"{db_path.name} check error: {e}"
×
207

208

209
def _check_profile_health(profile_path: pathlib.Path) -> _ProfileHealthResult:
1✔
210
    """Chrome プロファイルの健全性をチェック
211

212
    Args:
213
        profile_path: Chrome プロファイルのディレクトリパス
214

215
    Returns:
216
        ProfileHealthResult: チェック結果
217

218
    """
219
    errors: list[str] = []
1✔
220
    has_lock_files = False
1✔
221
    has_corrupted_json = False
1✔
222
    has_corrupted_db = False
1✔
223

224
    if not profile_path.exists():
1✔
225
        # プロファイルが存在しない場合は健全(新規作成される)
226
        return _ProfileHealthResult(is_healthy=True, errors=[])
1✔
227

228
    default_path = profile_path / "Default"
1✔
229

230
    # 1. ロックファイルのチェック
231
    lock_files = ["SingletonLock", "SingletonSocket", "SingletonCookie"]
1✔
232
    existing_locks = []
1✔
233
    for lock_file in lock_files:
1✔
234
        lock_path = profile_path / lock_file
1✔
235
        if lock_path.exists() or lock_path.is_symlink():
1✔
236
            existing_locks.append(lock_file)
1✔
237
            has_lock_files = True
1✔
238
    if existing_locks:
1✔
239
        errors.append(f"Lock files exist: {', '.join(existing_locks)}")
1✔
240

241
    # 2. Local State の JSON チェック
242
    local_state_error = _check_json_file(profile_path / "Local State")
1✔
243
    if local_state_error:
1✔
244
        errors.append(local_state_error)
1✔
245
        has_corrupted_json = True
1✔
246

247
    # 3. Preferences の JSON チェック
248
    if default_path.exists():
1✔
249
        prefs_error = _check_json_file(default_path / "Preferences")
1✔
250
        if prefs_error:
1✔
251
            errors.append(prefs_error)
×
252
            has_corrupted_json = True
×
253

254
        # 4. SQLite データベースの整合性チェック
255
        for db_name in ["Cookies", "History", "Web Data"]:
1✔
256
            db_error = _check_sqlite_db(default_path / db_name)
1✔
257
            if db_error:
1✔
258
                errors.append(db_error)
1✔
259
                has_corrupted_db = True
1✔
260

261
    is_healthy = len(errors) == 0
1✔
262

263
    return _ProfileHealthResult(
1✔
264
        is_healthy=is_healthy,
265
        errors=errors,
266
        has_lock_files=has_lock_files,
267
        has_corrupted_json=has_corrupted_json,
268
        has_corrupted_db=has_corrupted_db,
269
    )
270

271

272
def _recover_corrupted_profile(profile_path: pathlib.Path) -> bool:
1✔
273
    """破損したプロファイルをバックアップして新規作成を可能にする
274

275
    Args:
276
        profile_path: Chrome プロファイルのディレクトリパス
277

278
    Returns:
279
        bool: リカバリが成功したかどうか
280

281
    """
282
    if not profile_path.exists():
1✔
283
        return True
1✔
284

285
    # バックアップ先を決定(タイムスタンプ付き)
286
    timestamp = my_lib.time.now().strftime("%Y%m%d_%H%M%S")
1✔
287
    backup_path = profile_path.parent / f"{profile_path.name}.corrupted.{timestamp}"
1✔
288

289
    try:
1✔
290
        shutil.move(str(profile_path), str(backup_path))
1✔
291
        logging.warning(
1✔
292
            "Corrupted profile moved to backup: %s -> %s",
293
            profile_path,
294
            backup_path,
295
        )
296
        return True
1✔
297
    except Exception:
×
298
        logging.exception("Failed to backup corrupted profile")
×
299
        return False
×
300

301

302
def _cleanup_profile_lock(profile_path: pathlib.Path) -> None:
1✔
303
    """プロファイルのロックファイルを削除する"""
304
    lock_files = ["SingletonLock", "SingletonSocket", "SingletonCookie"]
1✔
305
    found_locks = []
1✔
306
    for lock_file in lock_files:
1✔
307
        lock_path = profile_path / lock_file
1✔
308
        if lock_path.exists() or lock_path.is_symlink():
1✔
309
            found_locks.append(lock_path)
1✔
310

311
    if found_locks:
1✔
312
        logging.warning("Profile lock files found: %s", ", ".join(str(p.name) for p in found_locks))
1✔
313
        for lock_path in found_locks:
1✔
314
            try:
1✔
315
                lock_path.unlink()
1✔
316
            except OSError as e:
×
317
                logging.warning("Failed to remove lock file %s: %s", lock_path, e)
×
318

319

320
def _is_running_in_container() -> bool:
1✔
321
    """コンテナ内で実行中かどうかを判定"""
322
    return pathlib.Path("/.dockerenv").exists()
1✔
323

324

325
def _cleanup_orphaned_chrome_processes_in_container() -> None:
1✔
326
    """コンテナ内で実行中の場合のみ、残った Chrome プロセスをクリーンアップ
327

328
    NOTE: プロセスツリーに関係なくプロセス名で一律終了するのはコンテナ内限定
329
    """
330
    if not _is_running_in_container():
×
331
        return
×
332

333
    for proc in psutil.process_iter(["pid", "name"]):
×
334
        try:
×
335
            proc_name = proc.info["name"].lower() if proc.info["name"] else ""
×
336
            if "chrome" in proc_name:
×
337
                logging.info("Terminating orphaned Chrome process: PID %d", proc.info["pid"])
×
338
                os.kill(proc.info["pid"], signal.SIGTERM)
×
339
        except (psutil.NoSuchProcess, psutil.AccessDenied, ProcessLookupError, OSError):
×
340
            pass
×
341
    time.sleep(1)
×
342

343

344
def _get_actual_profile_name(profile_name: str) -> str:
1✔
345
    """PYTEST_XDIST_WORKER を考慮した実際のプロファイル名を取得"""
346
    suffix = os.environ.get("PYTEST_XDIST_WORKER", None)
×
347
    return profile_name + ("." + suffix if suffix is not None else "")
×
348

349

350
def delete_profile(profile_name: str, data_path: pathlib.Path) -> bool:
1✔
351
    """Chrome プロファイルを削除する
352

353
    Args:
354
        profile_name: プロファイル名
355
        data_path: データディレクトリのパス
356

357
    Returns:
358
        bool: 削除が成功したかどうか
359

360
    """
361
    actual_profile_name = _get_actual_profile_name(profile_name)
×
362
    profile_path = data_path / "chrome" / actual_profile_name
×
363

364
    if not profile_path.exists():
×
365
        logging.info("Profile does not exist: %s", profile_path)
×
366
        return True
×
367

368
    try:
×
369
        shutil.rmtree(profile_path)
×
370
        logging.warning("Deleted Chrome profile: %s", profile_path)
×
371
        return True
×
372
    except Exception:
×
373
        logging.exception("Failed to delete Chrome profile: %s", profile_path)
×
374
        return False
×
375

376

377
def create_driver(  # noqa: PLR0913
1✔
378
    profile_name: str,
379
    data_path: pathlib.Path,
380
    is_headless: bool = True,  # noqa: FBT001
381
    clean_profile: bool = False,  # noqa: FBT001
382
    auto_recover: bool = True,  # noqa: FBT001
383
    use_subprocess: bool = True,  # noqa: FBT001
384
) -> WebDriver:
385
    """Chrome WebDriver を作成する
386

387
    Args:
388
        profile_name: プロファイル名
389
        data_path: データディレクトリのパス
390
        is_headless: ヘッドレスモードで起動するか
391
        clean_profile: 起動前にロックファイルを削除するか
392
        auto_recover: プロファイル破損時に自動リカバリするか
393
        use_subprocess: サブプロセスで Chrome を起動するか
394

395
    """
396
    # NOTE: ルートロガーの出力レベルを変更した場合でも Selenium 関係は抑制する
397
    logging.getLogger("urllib3.connectionpool").setLevel(logging.WARNING)
×
398
    logging.getLogger("selenium.webdriver.common.selenium_manager").setLevel(logging.WARNING)
×
399
    logging.getLogger("selenium.webdriver.remote.remote_connection").setLevel(logging.WARNING)
×
400

401
    actual_profile_name = _get_actual_profile_name(profile_name)
×
402
    profile_path = data_path / "chrome" / actual_profile_name
×
403

404
    # プロファイル健全性チェック
405
    health = _check_profile_health(profile_path)
×
406
    if not health.is_healthy:
×
407
        logging.warning("Profile health check failed: %s", ", ".join(health.errors))
×
408

409
        if health.has_lock_files and not (health.has_corrupted_json or health.has_corrupted_db):
×
410
            # ロックファイルのみの問題なら削除して続行
411
            logging.info("Cleaning up lock files only")
×
412
            _cleanup_profile_lock(profile_path)
×
413
        elif auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
414
            # JSON または DB が破損している場合はプロファイルをリカバリ
415
            logging.warning("Profile is corrupted, attempting recovery")
×
416
            if _recover_corrupted_profile(profile_path):
×
417
                logging.info("Profile recovery successful, will create new profile")
×
418
            else:
419
                logging.error("Profile recovery failed")
×
420

421
    if clean_profile:
×
422
        _cleanup_profile_lock(profile_path)
×
423

424
    # NOTE: 1回だけ自動リトライ
425
    try:
×
426
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess)
×
427
    except Exception as e:
×
428
        logging.warning("First attempt to create driver failed: %s", e)
×
429

430
        # コンテナ内で実行中の場合のみ、残った Chrome プロセスをクリーンアップ
431
        _cleanup_orphaned_chrome_processes_in_container()
×
432

433
        # プロファイルのロックファイルを削除
434
        _cleanup_profile_lock(profile_path)
×
435

436
        # 再度健全性チェック
437
        health = _check_profile_health(profile_path)
×
438
        if not health.is_healthy and auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
439
            logging.warning("Profile still corrupted after first attempt, recovering")
×
440
            _recover_corrupted_profile(profile_path)
×
441

442
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess)
×
443

444

445
def xpath_exists(driver: WebDriver, xpath: str) -> bool:
1✔
446
    return len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0
×
447

448

449
def get_text(
1✔
450
    driver: WebDriver,
451
    xpath: str,
452
    safe_text: str,
453
    wait: WebDriverWait[WebDriver] | None = None,
454
) -> str:
455
    if wait is not None:
×
456
        wait.until(
×
457
            selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(
458
                (selenium.webdriver.common.by.By.XPATH, xpath)
459
            )
460
        )
461

462
    if len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0:
×
463
        return driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).text.strip()
×
464
    else:
465
        return safe_text
×
466

467

468
def input_xpath(
1✔
469
    driver: WebDriver,
470
    xpath: str,
471
    text: str,
472
    wait: WebDriverWait[WebDriver] | None = None,
473
    is_warn: bool = True,  # noqa: FBT001
474
) -> bool:
475
    if wait is not None:
×
476
        wait.until(
×
477
            selenium.webdriver.support.expected_conditions.element_to_be_clickable(
478
                (selenium.webdriver.common.by.By.XPATH, xpath)
479
            )
480
        )
481
        time.sleep(0.05)
×
482

483
    if xpath_exists(driver, xpath):
×
484
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).send_keys(text)
×
485
        return True
×
486
    else:
487
        if is_warn:
×
488
            logging.warning("Element is not found: %s", xpath)
×
489
        return False
×
490

491

492
def click_xpath(
1✔
493
    driver: WebDriver,
494
    xpath: str,
495
    wait: WebDriverWait[WebDriver] | None = None,
496
    is_warn: bool = True,  # noqa: FBT001
497
    move: bool = False,  # noqa: FBT001
498
) -> bool:
499
    if wait is not None:
×
500
        wait.until(
×
501
            selenium.webdriver.support.expected_conditions.element_to_be_clickable(
502
                (selenium.webdriver.common.by.By.XPATH, xpath)
503
            )
504
        )
505
        time.sleep(0.05)
×
506

507
    if xpath_exists(driver, xpath):
×
508
        elem = driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath)
×
509
        if move:
×
510
            action = selenium.webdriver.common.action_chains.ActionChains(driver)
×
511
            action.move_to_element(elem)
×
512
            action.perform()
×
513

514
        elem.click()
×
515
        return True
×
516
    else:
517
        if is_warn:
×
518
            logging.warning("Element is not found: %s", xpath)
×
519
        return False
×
520

521

522
def is_display(driver: WebDriver, xpath: str) -> bool:
1✔
523
    return (len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0) and (
×
524
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).is_displayed()
525
    )
526

527

528
def random_sleep(sec: float) -> None:
1✔
529
    RATIO = 0.8
1✔
530

531
    time.sleep((sec * RATIO) + (sec * (1 - RATIO) * 2) * random.random())  # noqa: S311
1✔
532

533

534
def with_retry(
1✔
535
    func: Callable[[], T],
536
    max_retries: int = 3,
537
    delay: float = 1.0,
538
    exceptions: tuple[type[Exception], ...] = (Exception,),
539
    on_retry: Callable[[int, Exception], bool | None] | None = None,
540
) -> T:
541
    """リトライ付きで関数を実行
542

543
    全て失敗した場合は最後の例外を再スロー。
544
    呼び出し側で try/except してエラー処理を行う。
545

546
    Args:
547
        func: 実行する関数
548
        max_retries: 最大リトライ回数
549
        delay: リトライ間の待機秒数
550
        exceptions: リトライ対象の例外タプル
551
        on_retry: リトライ時のコールバック (attempt, exception)
552
            - None または True を返すとリトライを継続
553
            - False を返すとリトライを中止して例外を再スロー
554

555
    Returns:
556
        成功時は関数の戻り値
557

558
    Raises:
559
        最後の例外を再スロー
560

561
    """
562
    last_exception: Exception | None = None
×
563

564
    for attempt in range(max_retries):
×
565
        try:
×
566
            return func()
×
567
        except exceptions as e:
×
568
            last_exception = e
×
569
            if attempt < max_retries - 1:
×
570
                if on_retry:
×
571
                    should_continue = on_retry(attempt + 1, e)
×
572
                    if should_continue is False:
×
573
                        raise
×
574
                time.sleep(delay)
×
575

576
    if last_exception:
×
577
        raise last_exception
×
578
    raise RuntimeError("Unexpected state in with_retry")
×
579

580

581
def wait_patiently(
1✔
582
    driver: WebDriver,
583
    wait: WebDriverWait[WebDriver],
584
    target: Any,
585
) -> None:
586
    error: selenium.common.exceptions.TimeoutException | None = None
×
587
    for i in range(WAIT_RETRY_COUNT + 1):
×
588
        try:
×
589
            wait.until(target)
×
590
            return
×
591
        except selenium.common.exceptions.TimeoutException as e:
×
592
            logging.warning(
×
593
                "タイムアウトが発生しました。(%s in %s line %d)",
594
                inspect.stack()[1].function,
595
                inspect.stack()[1].filename,
596
                inspect.stack()[1].lineno,
597
            )
598
            error = e
×
599

600
            logging.info(i)
×
601
            if i != WAIT_RETRY_COUNT:
×
602
                logging.info("refresh")
×
603
                driver.refresh()
×
604

605
    if error is not None:
×
606
        raise error
×
607

608

609
def dump_page(
1✔
610
    driver: WebDriver,
611
    index: int,
612
    dump_path: pathlib.Path,
613
    stack_index: int = 1,
614
) -> None:
615
    name = inspect.stack()[stack_index].function.replace("<", "").replace(">", "")
×
616

617
    dump_path.mkdir(parents=True, exist_ok=True)
×
618

619
    png_path = dump_path / f"{name}_{index:02d}.png"
×
620
    htm_path = dump_path / f"{name}_{index:02d}.htm"
×
621

622
    driver.save_screenshot(str(png_path))
×
623

624
    with htm_path.open("w", encoding="utf-8") as f:
×
625
        f.write(driver.page_source)
×
626

627
    logging.info(
×
628
        "page dump: %02d from %s in %s line %d",
629
        index,
630
        inspect.stack()[stack_index].function,
631
        inspect.stack()[stack_index].filename,
632
        inspect.stack()[stack_index].lineno,
633
    )
634

635

636
def clear_cache(driver: WebDriver) -> None:
1✔
637
    driver.execute_cdp_cmd("Network.clearBrowserCache", {})
×
638

639

640
def set_japanese_locale(driver: WebDriver) -> None:
1✔
641
    """CDP を使って日本語ロケールを強制設定
642

643
    Chrome の起動オプションだけでは言語設定が変わってしまうことがあるため、
644
    CDP を使って Accept-Language ヘッダーとロケールを強制的に日本語に設定する。
645
    """
646
    try:
×
647
        # NOTE: Network.setExtraHTTPHeaders は Network.enable を先に呼ばないと機能しない
648
        driver.execute_cdp_cmd("Network.enable", {})
×
649
        driver.execute_cdp_cmd(
×
650
            "Network.setExtraHTTPHeaders",
651
            {"headers": {"Accept-Language": "ja-JP,ja;q=0.9"}},
652
        )
653
        driver.execute_cdp_cmd(
×
654
            "Emulation.setLocaleOverride",
655
            {"locale": "ja-JP"},
656
        )
657
        logging.debug("Japanese locale set via CDP")
×
658
    except Exception:
×
659
        logging.warning("Failed to set Japanese locale via CDP")
×
660

661

662
def clean_dump(dump_path: pathlib.Path, keep_days: int = 1) -> None:
1✔
663
    if not dump_path.exists():
1✔
664
        return
1✔
665

666
    time_threshold = datetime.timedelta(keep_days)
1✔
667

668
    for item in dump_path.iterdir():
1✔
669
        if not item.is_file():
1✔
670
            continue
1✔
671
        try:
1✔
672
            time_diff = datetime.datetime.now(datetime.UTC) - datetime.datetime.fromtimestamp(
1✔
673
                item.stat().st_mtime, datetime.UTC
674
            )
675
        except FileNotFoundError:
×
676
            # ファイルが別プロセスにより削除された場合(SQLiteの一時ファイルなど)
677
            continue
×
678
        if time_diff > time_threshold:
1✔
679
            logging.warning("remove %s [%s day(s) old].", item.absolute(), f"{time_diff.days:,}")
1✔
680

681
            item.unlink(missing_ok=True)
1✔
682

683

684
def get_memory_info(driver: WebDriver) -> dict[str, Any]:
1✔
685
    """ブラウザのメモリ使用量を取得(単位: KB)"""
686
    total_bytes = subprocess.Popen(  # noqa: S602
×
687
        "smem -t -c pss -P chrome | tail -n 1",  # noqa: S607
688
        shell=True,
689
        stdout=subprocess.PIPE,
690
    ).communicate()[0]
691
    total = int(str(total_bytes, "utf-8").strip())  # smem の出力は KB 単位
×
692

693
    try:
×
694
        memory_info = driver.execute_cdp_cmd("Memory.getAllTimeSamplingProfile", {})
×
695
        heap_usage = driver.execute_cdp_cmd("Runtime.getHeapUsage", {})
×
696

697
        heap_used = heap_usage.get("usedSize", 0) // 1024  # bytes → KB
×
698
        heap_total = heap_usage.get("totalSize", 0) // 1024  # bytes → KB
×
699
    except Exception as e:
×
700
        logging.debug("Failed to get memory usage: %s", e)
×
701

702
        memory_info = None
×
703
        heap_used = 0
×
704
        heap_total = 0
×
705

706
    return {
×
707
        "total": total,
708
        "heap_used": heap_used,
709
        "heap_total": heap_total,
710
        "memory_info": memory_info,
711
    }
712

713

714
def log_memory_usage(driver: WebDriver) -> None:
1✔
715
    mem_info = get_memory_info(driver)
×
716
    logging.info(
×
717
        "Chrome memory: %s MB (JS heap: %s MB)",
718
        f"""{mem_info["total"] // 1024:,}""",
719
        f"""{mem_info["heap_used"] // 1024:,}""",
720
    )
721

722

723
def _warmup(
1✔
724
    driver: WebDriver,
725
    keyword: str,
726
    url_pattern: str,
727
    sleep_sec: int = 3,
728
) -> None:
729
    # NOTE: ダミーアクセスを行って BOT ではないと思わせる。(効果なさそう...)
730
    driver.get("https://www.yahoo.co.jp/")
×
731
    time.sleep(sleep_sec)
×
732

733
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(keyword)
×
734
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(
×
735
        selenium.webdriver.common.keys.Keys.ENTER
736
    )
737

738
    time.sleep(sleep_sec)
×
739

740
    driver.find_element(
×
741
        selenium.webdriver.common.by.By.XPATH, f'//a[contains(@href, "{url_pattern}")]'
742
    ).click()
743

744
    time.sleep(sleep_sec)
×
745

746

747
class browser_tab:  # noqa: N801
1✔
748
    """新しいブラウザタブで URL を開くコンテキストマネージャ"""
749

750
    def __init__(self, driver: WebDriver, url: str) -> None:
1✔
751
        """初期化
752

753
        Args:
754
            driver: WebDriver インスタンス
755
            url: 開く URL
756

757
        """
758
        self.driver = driver
1✔
759
        self.url = url
1✔
760
        self.original_window: str | None = None
1✔
761

762
    def __enter__(self) -> None:
1✔
763
        """新しいタブを開いて URL にアクセス"""
764
        self.original_window = self.driver.current_window_handle
1✔
765
        self.driver.execute_script("window.open('');")
1✔
766
        self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
767
        try:
1✔
768
            self.driver.get(self.url)
1✔
769
        except Exception:
×
770
            # NOTE: URL読み込みに失敗した場合もクリーンアップしてから例外を再送出
771
            self._cleanup()
×
772
            raise
×
773

774
    def _cleanup(self) -> None:
1✔
775
        """タブを閉じて元のウィンドウに戻る"""
776
        try:
1✔
777
            # 余分なタブを閉じる
778
            while len(self.driver.window_handles) > 1:
1✔
779
                self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
780
                self.driver.close()
1✔
781
            if self.original_window is not None:
1✔
782
                self.driver.switch_to.window(self.original_window)
1✔
783
            time.sleep(0.1)
1✔
784
        except Exception:
1✔
785
            # NOTE: Chromeがクラッシュした場合は無視(既に終了しているため操作不可)
786
            logging.exception("タブのクリーンアップに失敗しました(Chromeがクラッシュした可能性があります)")
1✔
787

788
    def _recover_from_error(self) -> None:
1✔
789
        """エラー後にブラウザの状態を回復する"""
790
        try:
×
791
            # ページロードタイムアウトをリセット(負の値になっている可能性があるため)
792
            self.driver.set_page_load_timeout(30)
×
793

794
            # about:blank に移動してレンダラーの状態をリセット
795
            self.driver.get("about:blank")
×
796
            time.sleep(0.5)
×
797
        except Exception:
×
798
            logging.warning("ブラウザの回復に失敗しました")
×
799

800
    def __exit__(
1✔
801
        self,
802
        exception_type: type[BaseException] | None,
803
        exception_value: BaseException | None,
804
        traceback: types.TracebackType | None,
805
    ) -> None:
806
        """タブを閉じて元のウィンドウに戻る"""
807
        self._cleanup()
1✔
808

809
        # 例外が発生した場合はブラウザの状態を回復
810
        if exception_type is not None:
1✔
811
            self._recover_from_error()
×
812

813

814
class error_handler:  # noqa: N801
1✔
815
    """Selenium操作時のエラーハンドリング用コンテキストマネージャ
816

817
    エラー発生時に自動でログ出力、スクリーンショット取得、コールバック呼び出しを行う。
818

819
    Args:
820
        driver: WebDriver インスタンス
821
        message: ログに出力するエラーメッセージ
822
        on_error: エラー時に呼ばれるコールバック関数 (exception, screenshot: PIL.Image.Image | None) -> None
823
        capture_screenshot: スクリーンショットを自動取得するか(デフォルト: True)
824
        reraise: 例外を再送出するか(デフォルト: True)
825

826
    Attributes:
827
        exception: 発生した例外(エラーがなければ None)
828
        screenshot: 取得したスクリーンショット(PIL.Image.Image、取得失敗時は None)
829

830
    Examples:
831
        基本的な使用方法::
832

833
            with my_lib.selenium_util.error_handler(driver, message="ログイン処理に失敗") as handler:
834
                driver.get(login_url)
835
                driver.find_element(...).click()
836

837
        コールバック付き(Slack通知など)::
838

839
            def notify(exc, screenshot):
840
                slack.error("エラー発生", str(exc), screenshot)
841

842
            with my_lib.selenium_util.error_handler(
843
                driver,
844
                message="クロール処理に失敗",
845
                on_error=notify,
846
            ):
847
                crawl_page(driver)
848

849
        例外を抑制して続行::
850

851
            with my_lib.selenium_util.error_handler(driver, reraise=False) as handler:
852
                risky_operation()
853

854
            if handler.exception:
855
                logging.warning("処理をスキップしました")
856

857
    """
858

859
    def __init__(
1✔
860
        self,
861
        driver: WebDriver,
862
        message: str = "Selenium operation failed",
863
        on_error: Callable[[Exception, PIL.Image.Image | None], None] | None = None,
864
        capture_screenshot: bool = True,  # noqa: FBT001
865
        reraise: bool = True,  # noqa: FBT001
866
    ) -> None:
867
        """初期化"""
868
        self.driver = driver
1✔
869
        self.message = message
1✔
870
        self.on_error = on_error
1✔
871
        self.capture_screenshot = capture_screenshot
1✔
872
        self.reraise = reraise
1✔
873
        self.exception: Exception | None = None
1✔
874
        self.screenshot: PIL.Image.Image | None = None
1✔
875

876
    def __enter__(self) -> Self:
1✔
877
        """コンテキストマネージャの開始"""
878
        return self
1✔
879

880
    def __exit__(
1✔
881
        self,
882
        exception_type: type[BaseException] | None,
883
        exception_value: BaseException | None,
884
        traceback: types.TracebackType | None,
885
    ) -> bool:
886
        """コンテキストマネージャの終了、エラー処理を実行"""
887
        if exception_value is None:
1✔
888
            return False
1✔
889

890
        # 例外を記録
891
        if isinstance(exception_value, Exception):
1✔
892
            self.exception = exception_value
1✔
893
        else:
894
            # BaseException(KeyboardInterrupt など)は処理せず再送出
895
            return False
×
896

897
        # ログ出力
898
        logging.exception(self.message)
1✔
899

900
        # スクリーンショット取得
901
        if self.capture_screenshot:
1✔
902
            try:
1✔
903
                screenshot_bytes = self.driver.get_screenshot_as_png()
1✔
904
                self.screenshot = PIL.Image.open(io.BytesIO(screenshot_bytes))
1✔
905
            except Exception:
1✔
906
                logging.debug("Failed to capture screenshot for error handling")
1✔
907

908
        # コールバック呼び出し
909
        if self.on_error is not None:
1✔
910
            try:
1✔
911
                self.on_error(self.exception, self.screenshot)
1✔
912
            except Exception:
×
913
                logging.exception("Error in on_error callback")
×
914

915
        # reraise=False なら例外を抑制
916
        return not self.reraise
1✔
917

918

919
def _is_chrome_related_process(process: psutil.Process) -> bool:
1✔
920
    """プロセスがChrome関連かどうかを判定"""
921
    try:
1✔
922
        process_name = process.name().lower()
1✔
923
        # Chrome関連のプロセス名パターン
924
        chrome_patterns = ["chrome", "chromium", "google-chrome", "undetected_chro"]
1✔
925
        # chromedriverは除外
926
        if "chromedriver" in process_name:
1✔
927
            return False
1✔
928
        return any(pattern in process_name for pattern in chrome_patterns)
1✔
929
    except (psutil.NoSuchProcess, psutil.AccessDenied):
1✔
930
        return False
1✔
931

932

933
def _get_chrome_processes_by_pgid(chromedriver_pid: int, existing_pids: set[int]) -> list[int]:
1✔
934
    """プロセスグループIDで追加のChrome関連プロセスを取得"""
935
    additional_pids = []
×
936
    try:
×
937
        pgid = os.getpgid(chromedriver_pid)
×
938
        for proc in psutil.process_iter(["pid", "name", "ppid"]):
×
939
            if proc.info["pid"] in existing_pids:
×
940
                continue
×
941
            try:
×
942
                if os.getpgid(proc.info["pid"]) == pgid:
×
943
                    proc_obj = psutil.Process(proc.info["pid"])
×
944
                    if _is_chrome_related_process(proc_obj):
×
945
                        additional_pids.append(proc.info["pid"])
×
946
                        logging.debug(
×
947
                            "Found Chrome-related process by pgid: PID %d, name: %s",
948
                            proc.info["pid"],
949
                            proc.info["name"],
950
                        )
951
            except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
×
952
                pass
×
953
    except (OSError, psutil.NoSuchProcess):
×
954
        logging.debug("Failed to get process group ID for chromedriver")
×
955
    return additional_pids
×
956

957

958
def _get_chrome_related_processes(driver: WebDriver) -> list[int]:
1✔
959
    """Chrome関連の全子プロセスを取得
960

961
    undetected_chromedriver 使用時、Chrome プロセスは chromedriver の子ではなく
962
    Python プロセスの直接の子として起動されることがあるため、両方を検索する。
963
    """
964
    chrome_pids = set()
×
965

966
    # 1. driver.service.process の子プロセスを検索
967
    try:
×
968
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "process"):  # type: ignore[attr-defined]
×
969
            process = driver.service.process  # type: ignore[attr-defined]
×
970
            if process and hasattr(process, "pid"):
×
971
                chromedriver_pid = process.pid
×
972

973
                # psutilでプロセス階層を取得
974
                parent_process = psutil.Process(chromedriver_pid)
×
975
                children = parent_process.children(recursive=True)
×
976

977
                for child in children:
×
978
                    chrome_pids.add(child.pid)
×
979
                    logging.debug(
×
980
                        "Found Chrome-related process (service child): PID %d, name: %s",
981
                        child.pid,
982
                        child.name(),
983
                    )
984
    except Exception:
×
985
        logging.exception("Failed to get Chrome-related processes from service")
×
986

987
    # 2. 現在の Python プロセスの全子孫から Chrome 関連プロセスを検索
988
    try:
×
989
        current_process = psutil.Process()
×
990
        all_children = current_process.children(recursive=True)
×
991

992
        for child in all_children:
×
993
            if child.pid in chrome_pids:
×
994
                continue
×
995
            try:
×
996
                if _is_chrome_related_process(child):
×
997
                    chrome_pids.add(child.pid)
×
998
                    logging.debug(
×
999
                        "Found Chrome-related process (python child): PID %d, name: %s",
1000
                        child.pid,
1001
                        child.name(),
1002
                    )
1003
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1004
                pass
×
1005
    except Exception:
×
1006
        logging.exception("Failed to get Chrome-related processes from python children")
×
1007

1008
    return list(chrome_pids)
×
1009

1010

1011
def _send_signal_to_processes(pids: list[int], sig: signal.Signals, signal_name: str) -> None:
1✔
1012
    """プロセスリストに指定されたシグナルを送信"""
1013
    errors = []
×
1014
    for pid in pids:
×
1015
        try:
×
1016
            # プロセス名を取得
1017
            try:
×
1018
                process = psutil.Process(pid)
×
1019
                process_name = process.name()
×
1020
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1021
                process_name = "unknown"
×
1022

1023
            if sig == signal.SIGKILL:
×
1024
                # プロセスがまだ存在するかチェック
1025
                os.kill(pid, 0)  # シグナル0は存在確認
×
1026
            os.kill(pid, sig)
×
1027
            logging.info("Sent %s to process: PID %d (%s)", signal_name, pid, process_name)
×
1028
        except (ProcessLookupError, OSError) as e:
×
1029
            # プロセスが既に終了している場合は無視
1030
            errors.append((pid, e))
×
1031

1032
    # エラーが発生した場合はまとめてログ出力
1033
    if errors:
×
1034
        logging.debug("Failed to send %s to some processes: %s", signal_name, errors)
×
1035

1036

1037
def _terminate_chrome_processes(chrome_pids: list[int], timeout: float = 5.0) -> None:
1✔
1038
    """Chrome関連プロセスを段階的に終了
1039

1040
    Args:
1041
        chrome_pids: 終了対象のプロセスIDリスト
1042
        timeout: SIGTERM後にプロセス終了を待機する最大時間(秒)
1043

1044
    """
1045
    if not chrome_pids:
×
1046
        return
×
1047

1048
    # 優雅な終了(SIGTERM)
1049
    _send_signal_to_processes(chrome_pids, signal.SIGTERM, "SIGTERM")
×
1050

1051
    # プロセスの終了を待機(ポーリング)
1052
    remaining_pids = list(chrome_pids)
×
1053
    poll_interval = 0.2
×
1054
    elapsed = 0.0
×
1055

1056
    while remaining_pids and elapsed < timeout:
×
1057
        time.sleep(poll_interval)
×
1058
        elapsed += poll_interval
×
1059

1060
        # まだ生存しているプロセスをチェック
1061
        still_alive = []
×
1062
        for pid in remaining_pids:
×
1063
            try:
×
1064
                if psutil.pid_exists(pid):
×
1065
                    process = psutil.Process(pid)
×
1066
                    if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
×
1067
                        still_alive.append(pid)
×
1068
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1069
                pass
×
1070

1071
        remaining_pids = still_alive
×
1072

1073
    # タイムアウト後もまだ残っているプロセスにのみ SIGKILL を送信
1074
    if remaining_pids:
×
1075
        logging.warning(
×
1076
            "Chrome processes still alive after %.1fs, sending SIGKILL to %d processes",
1077
            elapsed,
1078
            len(remaining_pids),
1079
        )
1080
        _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1081

1082

1083
def _reap_single_process(pid: int) -> None:
1✔
1084
    """単一プロセスをwaitpidで回収"""
1085
    try:
×
1086
        # ノンブロッキングでwaitpid
1087
        result_pid, status = os.waitpid(pid, os.WNOHANG)
×
1088
        if result_pid == pid:
×
1089
            # プロセス名を取得
1090
            try:
×
1091
                process = psutil.Process(pid)
×
1092
                process_name = process.name()
×
1093
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1094
                process_name = "unknown"
×
1095
            logging.debug("Reaped Chrome process: PID %d (%s)", pid, process_name)
×
1096
    except (ChildProcessError, OSError):
×
1097
        # 子プロセスでない場合や既に回収済みの場合は無視
1098
        pass
×
1099

1100

1101
def _reap_chrome_processes(chrome_pids: list[int]) -> None:
1✔
1102
    """Chrome関連プロセスを明示的に回収してゾンビ化を防ぐ"""
1103
    for pid in chrome_pids:
×
1104
        _reap_single_process(pid)
×
1105

1106

1107
def _get_remaining_chrome_pids(chrome_pids: list[int]) -> list[int]:
1✔
1108
    """指定されたPIDリストから、まだ生存しているChrome関連プロセスを取得"""
1109
    remaining = []
×
1110
    for pid in chrome_pids:
×
1111
        try:
×
1112
            if psutil.pid_exists(pid):
×
1113
                process = psutil.Process(pid)
×
1114
                if (
×
1115
                    process.is_running()
1116
                    and process.status() != psutil.STATUS_ZOMBIE
1117
                    and _is_chrome_related_process(process)
1118
                ):
1119
                    remaining.append(pid)
×
1120
        except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1121
            pass
×
1122
    return remaining
×
1123

1124

1125
def _wait_for_processes_with_check(
1✔
1126
    chrome_pids: list[int],
1127
    timeout: float,
1128
    poll_interval: float = 0.2,
1129
    log_interval: float = 1.0,
1130
) -> list[int]:
1131
    """プロセスの終了を待機しつつ、残存プロセスをチェック
1132

1133
    Args:
1134
        chrome_pids: 監視対象のプロセスIDリスト
1135
        timeout: 最大待機時間(秒)
1136
        poll_interval: チェック間隔(秒)
1137
        log_interval: ログ出力間隔(秒)
1138

1139
    Returns:
1140
        タイムアウト後も残存しているプロセスIDのリスト
1141

1142
    """
1143
    elapsed = 0.0
×
1144
    last_log_time = 0.0
×
1145
    remaining_pids = list(chrome_pids)
×
1146

1147
    while remaining_pids and elapsed < timeout:
×
1148
        time.sleep(poll_interval)
×
1149
        elapsed += poll_interval
×
1150
        remaining_pids = _get_remaining_chrome_pids(remaining_pids)
×
1151

1152
        if remaining_pids and (elapsed - last_log_time) >= log_interval:
×
1153
            logging.info(
×
1154
                "Found %d remaining Chrome processes after %.0fs",
1155
                len(remaining_pids),
1156
                elapsed,
1157
            )
1158
            last_log_time = elapsed
×
1159

1160
    return remaining_pids
×
1161

1162

1163
def quit_driver_gracefully(  # noqa: C901
1✔
1164
    driver: WebDriver | None,
1165
    wait_sec: float = 5.0,
1166
    sigterm_wait_sec: float = 5.0,
1167
    sigkill_wait_sec: float = 5.0,
1168
) -> None:
1169
    """Chrome WebDriverを確実に終了する
1170

1171
    終了フロー:
1172
    1. driver.quit() を呼び出し
1173
    2. wait_sec 秒待機しつつプロセス終了をチェック
1174
    3. 残存プロセスがあれば SIGTERM を送信
1175
    4. sigterm_wait_sec 秒待機しつつプロセス終了をチェック
1176
    5. 残存プロセスがあれば SIGKILL を送信
1177
    6. sigkill_wait_sec 秒待機
1178

1179
    Args:
1180
        driver: 終了する WebDriver インスタンス
1181
        wait_sec: quit 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1182
        sigterm_wait_sec: SIGTERM 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1183
        sigkill_wait_sec: SIGKILL 後にプロセス回収を待機する秒数(デフォルト: 5秒)
1184

1185
    """
1186
    if driver is None:
1✔
1187
        return
1✔
1188

1189
    # quit前にChrome関連プロセスを記録
1190
    chrome_pids_before = _get_chrome_related_processes(driver)
1✔
1191

1192
    try:
1✔
1193
        # WebDriverの正常終了を試行(これがタブのクローズも含む)
1194
        driver.quit()
1✔
1195
        logging.info("WebDriver quit successfully")
1✔
1196
    except Exception:
1✔
1197
        logging.warning("Failed to quit driver normally", exc_info=True)
1✔
1198
    finally:
1199
        # undetected_chromedriver の __del__ がシャットダウン時に再度呼ばれるのを防ぐ
1200
        if hasattr(driver, "_has_quit"):
1✔
1201
            driver._has_quit = True  # type: ignore[attr-defined]  # noqa: SLF001
1✔
1202

1203
    # ChromeDriverサービスの停止を試行
1204
    try:
1✔
1205
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "stop"):  # type: ignore[attr-defined]
1✔
1206
            driver.service.stop()  # type: ignore[attr-defined]
×
1207
    except (ConnectionResetError, OSError):
×
1208
        # Chrome が既に終了している場合は無視
1209
        logging.debug("Chrome service already stopped")
×
1210
    except Exception:
×
1211
        logging.warning("Failed to stop Chrome service", exc_info=True)
×
1212

1213
    # Step 1: quit 後に wait_sec 秒待機しつつプロセス終了をチェック
1214
    remaining_pids = _wait_for_processes_with_check(chrome_pids_before, wait_sec)
1✔
1215

1216
    if not remaining_pids:
1✔
1217
        logging.debug("All Chrome processes exited normally")
1✔
1218
        return
1✔
1219

1220
    # Step 2: 残存プロセスに SIGTERM を送信
1221
    logging.info(
×
1222
        "Found %d remaining Chrome processes after %.0fs, sending SIGTERM",
1223
        len(remaining_pids),
1224
        wait_sec,
1225
    )
1226
    _send_signal_to_processes(remaining_pids, signal.SIGTERM, "SIGTERM")
×
1227

1228
    # Step 3: SIGTERM 後に sigterm_wait_sec 秒待機しつつプロセス終了をチェック
1229
    remaining_pids = _wait_for_processes_with_check(remaining_pids, sigterm_wait_sec)
×
1230

1231
    if not remaining_pids:
×
1232
        logging.info("All Chrome processes exited after SIGTERM")
×
1233
        _reap_chrome_processes(chrome_pids_before)
×
1234
        return
×
1235

1236
    # Step 4: 残存プロセスに SIGKILL を送信
1237
    logging.warning(
×
1238
        "Chrome processes still alive after SIGTERM + %.1fs, sending SIGKILL to %d processes",
1239
        sigterm_wait_sec,
1240
        len(remaining_pids),
1241
    )
1242
    _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1243

1244
    # Step 5: SIGKILL 後に sigkill_wait_sec 秒待機してプロセス回収
1245
    time.sleep(sigkill_wait_sec)
×
1246
    _reap_chrome_processes(chrome_pids_before)
×
1247

1248
    # 最終チェック:まだ残っているプロセスがあるか確認
1249
    still_remaining = _get_remaining_chrome_pids(remaining_pids)
×
1250

1251
    # 回収できなかったプロセスについて警告
1252
    if still_remaining:
×
1253
        for pid in still_remaining:
×
1254
            try:
×
1255
                process = psutil.Process(pid)
×
1256
                logging.warning("Failed to collect Chrome-related process: PID %d (%s)", pid, process.name())
×
1257
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1258
                pass
×
1259

1260

1261
if __name__ == "__main__":
1262
    import pathlib
1263

1264
    import docopt
1265
    import selenium.webdriver.support.wait
1266

1267
    import my_lib.config
1268
    import my_lib.logger
1269

1270
    assert __doc__ is not None  # noqa: S101
1271
    args = docopt.docopt(__doc__)
1272

1273
    config_file = args["-c"]
1274
    debug_mode = args["-D"]
1275

1276
    my_lib.logger.init("test", level=logging.DEBUG if debug_mode else logging.INFO)
1277

1278
    config = my_lib.config.load(config_file)
1279

1280
    driver = create_driver("test", pathlib.Path(config["data"]["selenium"]))
1281
    wait = selenium.webdriver.support.wait.WebDriverWait(driver, 5)
1282

1283
    driver.get("https://www.google.com/")
1284
    wait.until(
1285
        selenium.webdriver.support.expected_conditions.presence_of_element_located(
1286
            (selenium.webdriver.common.by.By.XPATH, '//input[contains(@value, "Google")]')
1287
        )
1288
    )
1289

1290
    quit_driver_gracefully(driver)
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc