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

kimata / my-py-lib / 20691871150

04 Jan 2026 10:58AM UTC coverage: 64.546% (-0.2%) from 64.783%
20691871150

push

github

kimata
feat: コンテナの起動経過時間を取得する container_util.get_uptime() を追加

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

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

115 of 157 new or added lines in 37 files covered. (73.25%)

4 existing lines in 3 files now uncovered.

3095 of 4795 relevant lines covered (64.55%)

0.65 hits per line

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

32.77
/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 logging
1✔
20
import os
1✔
21
import pathlib
1✔
22
import random
1✔
23
import re
1✔
24
import signal
1✔
25
import subprocess
1✔
26
import time
1✔
27
from typing import TYPE_CHECKING, Any, Self, TypeVar
1✔
28

29
import PIL.Image
1✔
30
import psutil
1✔
31
import selenium
1✔
32
import selenium.common.exceptions
1✔
33
import selenium.webdriver.chrome.options
1✔
34
import selenium.webdriver.chrome.service
1✔
35
import selenium.webdriver.common.action_chains
1✔
36
import selenium.webdriver.common.by
1✔
37
import selenium.webdriver.common.keys
1✔
38
import selenium.webdriver.support.expected_conditions
1✔
39
import undetected_chromedriver
1✔
40

41
import my_lib.chrome_util
1✔
42
import my_lib.time
1✔
43

44
if TYPE_CHECKING:
45
    import types
46
    from collections.abc import Callable
47

48
    from selenium.webdriver.remote.webdriver import WebDriver
49
    from selenium.webdriver.support.wait import WebDriverWait
50

51
T = TypeVar("T")
1✔
52

53
WAIT_RETRY_COUNT: int = 1
1✔
54

55

56
class SeleniumError(Exception):
1✔
57
    """Selenium 関連エラーの基底クラス"""
58

59

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

76

77
def _create_driver_impl(
1✔
78
    profile_name: str,
79
    data_path: pathlib.Path,
80
    is_headless: bool,
81
    use_subprocess: bool,
82
) -> WebDriver:
83
    chrome_data_path = data_path / "chrome"
×
84
    log_path = data_path / "log"
×
85

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

91
    chrome_data_path.mkdir(parents=True, exist_ok=True)
×
92
    log_path.mkdir(parents=True, exist_ok=True)
×
93

94
    options = selenium.webdriver.chrome.options.Options()
×
95

96
    if is_headless:
×
97
        options.add_argument("--headless=new")
×
98

99
    options.add_argument("--no-sandbox")  # for Docker
×
100
    options.add_argument("--disable-dev-shm-usage")  # for Docker
×
101
    options.add_argument("--disable-gpu")
×
102

103
    options.add_argument("--disable-popup-blocking")
×
104
    options.add_argument("--disable-plugins")
×
105

106
    options.add_argument("--no-first-run")
×
107

108
    options.add_argument("--lang=ja-JP")
×
109
    options.add_argument("--window-size=1920,1080")
×
110

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

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

116
    options.add_argument("--enable-logging")
×
117
    options.add_argument("--v=1")
×
118

119
    chrome_log_file = log_path / f"chrome_{profile_name}.log"
×
120
    options.add_argument(f"--log-file={chrome_log_file!s}")
×
121

122
    if not is_headless:
×
123
        options.add_argument("--auto-open-devtools-for-tabs")
×
124

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

129
    chrome_version = _get_chrome_version()
×
130

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

136
    driver = undetected_chromedriver.Chrome(
×
137
        service=service,
138
        options=options,
139
        use_subprocess=use_subprocess,
140
        version_main=chrome_version,
141
        user_multi_procs=use_multi_procs,
142
    )
143

144
    driver.set_page_load_timeout(30)
×
145

146
    # CDP を使って日本語ロケールを強制設定
147
    set_japanese_locale(driver)
×
148

149
    return driver
×
150

151

152
def create_driver(
1✔
153
    profile_name: str,
154
    data_path: pathlib.Path,
155
    is_headless: bool = True,
156
    clean_profile: bool = False,
157
    auto_recover: bool = True,
158
    use_subprocess: bool = False,
159
) -> WebDriver:
160
    """Chrome WebDriver を作成する
161

162
    Args:
163
        profile_name: プロファイル名
164
        data_path: データディレクトリのパス
165
        is_headless: ヘッドレスモードで起動するか
166
        clean_profile: 起動前にロックファイルを削除するか
167
        auto_recover: プロファイル破損時に自動リカバリするか
168
        use_subprocess: サブプロセスで Chrome を起動するか
169

170
    """
171
    # NOTE: ルートロガーの出力レベルを変更した場合でも Selenium 関係は抑制する
172
    logging.getLogger("urllib3.connectionpool").setLevel(logging.WARNING)
×
173
    logging.getLogger("selenium.webdriver.common.selenium_manager").setLevel(logging.WARNING)
×
174
    logging.getLogger("selenium.webdriver.remote.remote_connection").setLevel(logging.WARNING)
×
175

176
    # NOTE: chrome_util の内部関数を使用(同一パッケージ内での使用は許容)
NEW
177
    actual_profile_name = my_lib.chrome_util._get_actual_profile_name(profile_name)
×
178
    profile_path = data_path / "chrome" / actual_profile_name
×
179

180
    # プロファイル健全性チェック
NEW
181
    health = my_lib.chrome_util._check_profile_health(profile_path)
×
182
    if not health.is_healthy:
×
183
        logging.warning("Profile health check failed: %s", ", ".join(health.errors))
×
184

185
        if health.has_lock_files and not (health.has_corrupted_json or health.has_corrupted_db):
×
186
            # ロックファイルのみの問題なら削除して続行
187
            logging.info("Cleaning up lock files only")
×
NEW
188
            my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
189
        elif auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
190
            # JSON または DB が破損している場合はプロファイルをリカバリ
191
            logging.warning("Profile is corrupted, attempting recovery")
×
NEW
192
            if my_lib.chrome_util._recover_corrupted_profile(profile_path):
×
193
                logging.info("Profile recovery successful, will create new profile")
×
194
            else:
195
                logging.error("Profile recovery failed")
×
196

197
    if clean_profile:
×
NEW
198
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
199

200
    # NOTE: 1回だけ自動リトライ
201
    try:
×
202
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess)
×
203
    except Exception as e:
×
204
        logging.warning("First attempt to create driver failed: %s", e)
×
205

206
        # コンテナ内で実行中の場合のみ、残った Chrome プロセスをクリーンアップ
NEW
207
        my_lib.chrome_util._cleanup_orphaned_chrome_processes_in_container()
×
208

209
        # プロファイルのロックファイルを削除
NEW
210
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
211

212
        # 再度健全性チェック
NEW
213
        health = my_lib.chrome_util._check_profile_health(profile_path)
×
214
        if not health.is_healthy and auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
215
            logging.warning("Profile still corrupted after first attempt, recovering")
×
NEW
216
            my_lib.chrome_util._recover_corrupted_profile(profile_path)
×
217

218
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess)
×
219

220

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

224

225
def get_text(
1✔
226
    driver: WebDriver,
227
    xpath: str,
228
    safe_text: str,
229
    wait: WebDriverWait[WebDriver] | None = None,
230
) -> str:
231
    if wait is not None:
×
232
        wait.until(
×
233
            selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(
234
                (selenium.webdriver.common.by.By.XPATH, xpath)
235
            )
236
        )
237

238
    if len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0:
×
239
        return driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).text.strip()
×
240
    else:
241
        return safe_text
×
242

243

244
def input_xpath(
1✔
245
    driver: WebDriver,
246
    xpath: str,
247
    text: str,
248
    wait: WebDriverWait[WebDriver] | None = None,
249
    is_warn: bool = True,
250
) -> bool:
251
    if wait is not None:
×
252
        wait.until(
×
253
            selenium.webdriver.support.expected_conditions.element_to_be_clickable(
254
                (selenium.webdriver.common.by.By.XPATH, xpath)
255
            )
256
        )
257
        time.sleep(0.05)
×
258

259
    if xpath_exists(driver, xpath):
×
260
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).send_keys(text)
×
261
        return True
×
262
    else:
263
        if is_warn:
×
264
            logging.warning("Element is not found: %s", xpath)
×
265
        return False
×
266

267

268
def click_xpath(
1✔
269
    driver: WebDriver,
270
    xpath: str,
271
    wait: WebDriverWait[WebDriver] | None = None,
272
    is_warn: bool = True,
273
    move: bool = False,
274
) -> bool:
275
    if wait is not None:
×
276
        wait.until(
×
277
            selenium.webdriver.support.expected_conditions.element_to_be_clickable(
278
                (selenium.webdriver.common.by.By.XPATH, xpath)
279
            )
280
        )
281
        time.sleep(0.05)
×
282

283
    if xpath_exists(driver, xpath):
×
284
        elem = driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath)
×
285
        if move:
×
286
            action = selenium.webdriver.common.action_chains.ActionChains(driver)
×
287
            action.move_to_element(elem)
×
288
            action.perform()
×
289

290
        elem.click()
×
291
        return True
×
292
    else:
293
        if is_warn:
×
294
            logging.warning("Element is not found: %s", xpath)
×
295
        return False
×
296

297

298
def is_display(driver: WebDriver, xpath: str) -> bool:
1✔
299
    return (len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0) and (
×
300
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).is_displayed()
301
    )
302

303

304
def random_sleep(sec: float) -> None:
1✔
305
    RATIO = 0.8
1✔
306

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

309

310
def with_retry(
1✔
311
    func: Callable[[], T],
312
    max_retries: int = 3,
313
    delay: float = 1.0,
314
    exceptions: tuple[type[Exception], ...] = (Exception,),
315
    on_retry: Callable[[int, Exception], bool | None] | None = None,
316
) -> T:
317
    """リトライ付きで関数を実行
318

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

322
    Args:
323
        func: 実行する関数
324
        max_retries: 最大リトライ回数
325
        delay: リトライ間の待機秒数
326
        exceptions: リトライ対象の例外タプル
327
        on_retry: リトライ時のコールバック (attempt, exception)
328
            - None または True を返すとリトライを継続
329
            - False を返すとリトライを中止して例外を再スロー
330

331
    Returns:
332
        成功時は関数の戻り値
333

334
    Raises:
335
        最後の例外を再スロー
336

337
    """
338
    last_exception: Exception | None = None
×
339

340
    for attempt in range(max_retries):
×
341
        try:
×
342
            return func()
×
343
        except exceptions as e:
×
344
            last_exception = e
×
345
            if attempt < max_retries - 1:
×
346
                if on_retry:
×
347
                    should_continue = on_retry(attempt + 1, e)
×
348
                    if should_continue is False:
×
349
                        raise
×
350
                time.sleep(delay)
×
351

352
    if last_exception:
×
353
        raise last_exception
×
354
    raise RuntimeError("Unexpected state in with_retry")
×
355

356

357
def wait_patiently(
1✔
358
    driver: WebDriver,
359
    wait: WebDriverWait[WebDriver],
360
    target: Any,
361
) -> None:
362
    error: selenium.common.exceptions.TimeoutException | None = None
×
363
    for i in range(WAIT_RETRY_COUNT + 1):
×
364
        try:
×
365
            wait.until(target)
×
366
            return
×
367
        except selenium.common.exceptions.TimeoutException as e:
×
368
            logging.warning(
×
369
                "タイムアウトが発生しました。(%s in %s line %d)",
370
                inspect.stack()[1].function,
371
                inspect.stack()[1].filename,
372
                inspect.stack()[1].lineno,
373
            )
374
            error = e
×
375

376
            logging.info(i)
×
377
            if i != WAIT_RETRY_COUNT:
×
378
                logging.info("refresh")
×
379
                driver.refresh()
×
380

381
    if error is not None:
×
382
        raise error
×
383

384

385
def dump_page(
1✔
386
    driver: WebDriver,
387
    index: int,
388
    dump_path: pathlib.Path,
389
    stack_index: int = 1,
390
) -> None:
391
    name = inspect.stack()[stack_index].function.replace("<", "").replace(">", "")
×
392

393
    dump_path.mkdir(parents=True, exist_ok=True)
×
394

395
    png_path = dump_path / f"{name}_{index:02d}.png"
×
396
    htm_path = dump_path / f"{name}_{index:02d}.htm"
×
397

398
    driver.save_screenshot(str(png_path))
×
399

400
    with htm_path.open("w", encoding="utf-8") as f:
×
401
        f.write(driver.page_source)
×
402

403
    logging.info(
×
404
        "page dump: %02d from %s in %s line %d",
405
        index,
406
        inspect.stack()[stack_index].function,
407
        inspect.stack()[stack_index].filename,
408
        inspect.stack()[stack_index].lineno,
409
    )
410

411

412
def clear_cache(driver: WebDriver) -> None:
1✔
413
    driver.execute_cdp_cmd("Network.clearBrowserCache", {})
×
414

415

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

419
    Chrome の起動オプションだけでは言語設定が変わってしまうことがあるため、
420
    CDP を使って Accept-Language ヘッダーとロケールを強制的に日本語に設定する。
421
    """
422
    try:
×
423
        # NOTE: Network.setExtraHTTPHeaders は Network.enable を先に呼ばないと機能しない
424
        driver.execute_cdp_cmd("Network.enable", {})
×
425
        driver.execute_cdp_cmd(
×
426
            "Network.setExtraHTTPHeaders",
427
            {"headers": {"Accept-Language": "ja-JP,ja;q=0.9"}},
428
        )
429
        driver.execute_cdp_cmd(
×
430
            "Emulation.setLocaleOverride",
431
            {"locale": "ja-JP"},
432
        )
433
        logging.debug("Japanese locale set via CDP")
×
434
    except Exception:
×
435
        logging.warning("Failed to set Japanese locale via CDP")
×
436

437

438
def clean_dump(dump_path: pathlib.Path, keep_days: int = 1) -> None:
1✔
439
    if not dump_path.exists():
1✔
440
        return
1✔
441

442
    time_threshold = datetime.timedelta(keep_days)
1✔
443

444
    for item in dump_path.iterdir():
1✔
445
        if not item.is_file():
1✔
446
            continue
1✔
447
        try:
1✔
448
            time_diff = datetime.datetime.now(datetime.UTC) - datetime.datetime.fromtimestamp(
1✔
449
                item.stat().st_mtime, datetime.UTC
450
            )
451
        except FileNotFoundError:
×
452
            # ファイルが別プロセスにより削除された場合(SQLiteの一時ファイルなど)
453
            continue
×
454
        if time_diff > time_threshold:
1✔
455
            logging.warning("remove %s [%s day(s) old].", item.absolute(), f"{time_diff.days:,}")
1✔
456

457
            item.unlink(missing_ok=True)
1✔
458

459

460
def get_memory_info(driver: WebDriver) -> dict[str, Any]:
1✔
461
    """ブラウザのメモリ使用量を取得(単位: KB)"""
462
    total_bytes = subprocess.Popen(  # noqa: S602
×
463
        "smem -t -c pss -P chrome | tail -n 1",  # noqa: S607
464
        shell=True,
465
        stdout=subprocess.PIPE,
466
    ).communicate()[0]
467
    total = int(str(total_bytes, "utf-8").strip())  # smem の出力は KB 単位
×
468

469
    try:
×
470
        memory_info = driver.execute_cdp_cmd("Memory.getAllTimeSamplingProfile", {})
×
471
        heap_usage = driver.execute_cdp_cmd("Runtime.getHeapUsage", {})
×
472

473
        heap_used = heap_usage.get("usedSize", 0) // 1024  # bytes → KB
×
474
        heap_total = heap_usage.get("totalSize", 0) // 1024  # bytes → KB
×
475
    except Exception as e:
×
476
        logging.debug("Failed to get memory usage: %s", e)
×
477

478
        memory_info = None
×
479
        heap_used = 0
×
480
        heap_total = 0
×
481

482
    return {
×
483
        "total": total,
484
        "heap_used": heap_used,
485
        "heap_total": heap_total,
486
        "memory_info": memory_info,
487
    }
488

489

490
def log_memory_usage(driver: WebDriver) -> None:
1✔
491
    mem_info = get_memory_info(driver)
×
492
    logging.info(
×
493
        "Chrome memory: %s MB (JS heap: %s MB)",
494
        f"""{mem_info["total"] // 1024:,}""",
495
        f"""{mem_info["heap_used"] // 1024:,}""",
496
    )
497

498

499
def _warmup(
1✔
500
    driver: WebDriver,
501
    keyword: str,
502
    url_pattern: str,
503
    sleep_sec: int = 3,
504
) -> None:
505
    # NOTE: ダミーアクセスを行って BOT ではないと思わせる。(効果なさそう...)
506
    driver.get("https://www.yahoo.co.jp/")
×
507
    time.sleep(sleep_sec)
×
508

509
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(keyword)
×
510
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(
×
511
        selenium.webdriver.common.keys.Keys.ENTER
512
    )
513

514
    time.sleep(sleep_sec)
×
515

516
    driver.find_element(
×
517
        selenium.webdriver.common.by.By.XPATH, f'//a[contains(@href, "{url_pattern}")]'
518
    ).click()
519

520
    time.sleep(sleep_sec)
×
521

522

523
class browser_tab:
1✔
524
    """新しいブラウザタブで URL を開くコンテキストマネージャ"""
525

526
    def __init__(self, driver: WebDriver, url: str) -> None:
1✔
527
        """初期化
528

529
        Args:
530
            driver: WebDriver インスタンス
531
            url: 開く URL
532

533
        """
534
        self.driver = driver
1✔
535
        self.url = url
1✔
536
        self.original_window: str | None = None
1✔
537

538
    def __enter__(self) -> None:
1✔
539
        """新しいタブを開いて URL にアクセス"""
540
        self.original_window = self.driver.current_window_handle
1✔
541
        self.driver.execute_script("window.open('');")
1✔
542
        self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
543
        try:
1✔
544
            self.driver.get(self.url)
1✔
545
        except Exception:
×
546
            # NOTE: URL読み込みに失敗した場合もクリーンアップしてから例外を再送出
547
            self._cleanup()
×
548
            raise
×
549

550
    def _cleanup(self) -> None:
1✔
551
        """タブを閉じて元のウィンドウに戻る"""
552
        try:
1✔
553
            # 余分なタブを閉じる
554
            while len(self.driver.window_handles) > 1:
1✔
555
                self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
556
                self.driver.close()
1✔
557
            if self.original_window is not None:
1✔
558
                self.driver.switch_to.window(self.original_window)
1✔
559
            time.sleep(0.1)
1✔
560
        except Exception:
1✔
561
            # NOTE: Chromeがクラッシュした場合は無視(既に終了しているため操作不可)
562
            logging.exception("タブのクリーンアップに失敗しました(Chromeがクラッシュした可能性があります)")
1✔
563

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

570
            # about:blank に移動してレンダラーの状態をリセット
571
            self.driver.get("about:blank")
×
572
            time.sleep(0.5)
×
573
        except Exception:
×
574
            logging.warning("ブラウザの回復に失敗しました")
×
575

576
    def __exit__(
1✔
577
        self,
578
        exception_type: type[BaseException] | None,
579
        exception_value: BaseException | None,
580
        traceback: types.TracebackType | None,
581
    ) -> None:
582
        """タブを閉じて元のウィンドウに戻る"""
583
        self._cleanup()
1✔
584

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

589

590
class error_handler:
1✔
591
    """Selenium操作時のエラーハンドリング用コンテキストマネージャ
592

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

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

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

606
    Examples:
607
        基本的な使用方法::
608

609
            with my_lib.selenium_util.error_handler(driver, message="ログイン処理に失敗") as handler:
610
                driver.get(login_url)
611
                driver.find_element(...).click()
612

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

615
            def notify(exc, screenshot):
616
                slack.error("エラー発生", str(exc), screenshot)
617

618
            with my_lib.selenium_util.error_handler(
619
                driver,
620
                message="クロール処理に失敗",
621
                on_error=notify,
622
            ):
623
                crawl_page(driver)
624

625
        例外を抑制して続行::
626

627
            with my_lib.selenium_util.error_handler(driver, reraise=False) as handler:
628
                risky_operation()
629

630
            if handler.exception:
631
                logging.warning("処理をスキップしました")
632

633
    """
634

635
    def __init__(
1✔
636
        self,
637
        driver: WebDriver,
638
        message: str = "Selenium operation failed",
639
        on_error: Callable[[Exception, PIL.Image.Image | None], None] | None = None,
640
        capture_screenshot: bool = True,
641
        reraise: bool = True,
642
    ) -> None:
643
        """初期化"""
644
        self.driver = driver
1✔
645
        self.message = message
1✔
646
        self.on_error = on_error
1✔
647
        self.capture_screenshot = capture_screenshot
1✔
648
        self.reraise = reraise
1✔
649
        self.exception: Exception | None = None
1✔
650
        self.screenshot: PIL.Image.Image | None = None
1✔
651

652
    def __enter__(self) -> Self:
1✔
653
        """コンテキストマネージャの開始"""
654
        return self
1✔
655

656
    def __exit__(
1✔
657
        self,
658
        exception_type: type[BaseException] | None,
659
        exception_value: BaseException | None,
660
        traceback: types.TracebackType | None,
661
    ) -> bool:
662
        """コンテキストマネージャの終了、エラー処理を実行"""
663
        if exception_value is None:
1✔
664
            return False
1✔
665

666
        # 例外を記録
667
        if isinstance(exception_value, Exception):
1✔
668
            self.exception = exception_value
1✔
669
        else:
670
            # BaseException(KeyboardInterrupt など)は処理せず再送出
671
            return False
×
672

673
        # ログ出力
674
        logging.exception(self.message)
1✔
675

676
        # スクリーンショット取得
677
        if self.capture_screenshot:
1✔
678
            try:
1✔
679
                screenshot_bytes = self.driver.get_screenshot_as_png()
1✔
680
                self.screenshot = PIL.Image.open(io.BytesIO(screenshot_bytes))
1✔
681
            except Exception:
1✔
682
                logging.debug("Failed to capture screenshot for error handling")
1✔
683

684
        # コールバック呼び出し
685
        if self.on_error is not None:
1✔
686
            try:
1✔
687
                self.on_error(self.exception, self.screenshot)
1✔
688
            except Exception:
×
689
                logging.exception("Error in on_error callback")
×
690

691
        # reraise=False なら例外を抑制
692
        return not self.reraise
1✔
693

694

695
def _is_chrome_related_process(process: psutil.Process) -> bool:
1✔
696
    """プロセスがChrome関連かどうかを判定"""
697
    try:
1✔
698
        process_name = process.name().lower()
1✔
699
        # Chrome関連のプロセス名パターン
700
        chrome_patterns = ["chrome", "chromium", "google-chrome", "undetected_chro"]
1✔
701
        # chromedriverは除外
702
        if "chromedriver" in process_name:
1✔
703
            return False
1✔
704
        return any(pattern in process_name for pattern in chrome_patterns)
1✔
705
    except (psutil.NoSuchProcess, psutil.AccessDenied):
1✔
706
        return False
1✔
707

708

709
def _get_chrome_processes_by_pgid(chromedriver_pid: int, existing_pids: set[int]) -> list[int]:
1✔
710
    """プロセスグループIDで追加のChrome関連プロセスを取得"""
711
    additional_pids = []
×
712
    try:
×
713
        pgid = os.getpgid(chromedriver_pid)
×
714
        for proc in psutil.process_iter(["pid", "name", "ppid"]):
×
715
            if proc.info["pid"] in existing_pids:
×
716
                continue
×
717
            try:
×
718
                if os.getpgid(proc.info["pid"]) == pgid:
×
719
                    proc_obj = psutil.Process(proc.info["pid"])
×
720
                    if _is_chrome_related_process(proc_obj):
×
721
                        additional_pids.append(proc.info["pid"])
×
722
                        logging.debug(
×
723
                            "Found Chrome-related process by pgid: PID %d, name: %s",
724
                            proc.info["pid"],
725
                            proc.info["name"],
726
                        )
727
            except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
×
728
                pass
×
729
    except (OSError, psutil.NoSuchProcess):
×
730
        logging.debug("Failed to get process group ID for chromedriver")
×
731
    return additional_pids
×
732

733

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

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

742
    # 1. driver.service.process の子プロセスを検索
743
    try:
×
744
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "process"):  # type: ignore[attr-defined]
×
745
            process = driver.service.process  # type: ignore[attr-defined]
×
746
            if process and hasattr(process, "pid"):
×
747
                chromedriver_pid = process.pid
×
748

749
                # psutilでプロセス階層を取得
750
                parent_process = psutil.Process(chromedriver_pid)
×
751
                children = parent_process.children(recursive=True)
×
752

753
                for child in children:
×
754
                    chrome_pids.add(child.pid)
×
755
                    logging.debug(
×
756
                        "Found Chrome-related process (service child): PID %d, name: %s",
757
                        child.pid,
758
                        child.name(),
759
                    )
760
    except Exception:
×
761
        logging.exception("Failed to get Chrome-related processes from service")
×
762

763
    # 2. 現在の Python プロセスの全子孫から Chrome 関連プロセスを検索
764
    try:
×
765
        current_process = psutil.Process()
×
766
        all_children = current_process.children(recursive=True)
×
767

768
        for child in all_children:
×
769
            if child.pid in chrome_pids:
×
770
                continue
×
771
            try:
×
772
                if _is_chrome_related_process(child):
×
773
                    chrome_pids.add(child.pid)
×
774
                    logging.debug(
×
775
                        "Found Chrome-related process (python child): PID %d, name: %s",
776
                        child.pid,
777
                        child.name(),
778
                    )
779
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
780
                pass
×
781
    except Exception:
×
782
        logging.exception("Failed to get Chrome-related processes from python children")
×
783

784
    return list(chrome_pids)
×
785

786

787
def _send_signal_to_processes(pids: list[int], sig: signal.Signals, signal_name: str) -> None:
1✔
788
    """プロセスリストに指定されたシグナルを送信"""
789
    errors = []
×
790
    for pid in pids:
×
791
        try:
×
792
            # プロセス名を取得
793
            try:
×
794
                process = psutil.Process(pid)
×
795
                process_name = process.name()
×
796
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
797
                process_name = "unknown"
×
798

799
            if sig == signal.SIGKILL:
×
800
                # プロセスがまだ存在するかチェック
801
                os.kill(pid, 0)  # シグナル0は存在確認
×
802
            os.kill(pid, sig)
×
803
            logging.info("Sent %s to process: PID %d (%s)", signal_name, pid, process_name)
×
804
        except (ProcessLookupError, OSError) as e:
×
805
            # プロセスが既に終了している場合は無視
806
            errors.append((pid, e))
×
807

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

812

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

816
    Args:
817
        chrome_pids: 終了対象のプロセスIDリスト
818
        timeout: SIGTERM後にプロセス終了を待機する最大時間(秒)
819

820
    """
821
    if not chrome_pids:
×
822
        return
×
823

824
    # 優雅な終了(SIGTERM)
825
    _send_signal_to_processes(chrome_pids, signal.SIGTERM, "SIGTERM")
×
826

827
    # プロセスの終了を待機(ポーリング)
828
    remaining_pids = list(chrome_pids)
×
829
    poll_interval = 0.2
×
830
    elapsed = 0.0
×
831

832
    while remaining_pids and elapsed < timeout:
×
833
        time.sleep(poll_interval)
×
834
        elapsed += poll_interval
×
835

836
        # まだ生存しているプロセスをチェック
837
        still_alive = []
×
838
        for pid in remaining_pids:
×
839
            try:
×
840
                if psutil.pid_exists(pid):
×
841
                    process = psutil.Process(pid)
×
842
                    if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
×
843
                        still_alive.append(pid)
×
844
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
845
                pass
×
846

847
        remaining_pids = still_alive
×
848

849
    # タイムアウト後もまだ残っているプロセスにのみ SIGKILL を送信
850
    if remaining_pids:
×
851
        logging.warning(
×
852
            "Chrome processes still alive after %.1fs, sending SIGKILL to %d processes",
853
            elapsed,
854
            len(remaining_pids),
855
        )
856
        _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
857

858

859
def _reap_single_process(pid: int) -> None:
1✔
860
    """単一プロセスをwaitpidで回収"""
861
    try:
×
862
        # ノンブロッキングでwaitpid
863
        result_pid, status = os.waitpid(pid, os.WNOHANG)
×
864
        if result_pid == pid:
×
865
            # プロセス名を取得
866
            try:
×
867
                process = psutil.Process(pid)
×
868
                process_name = process.name()
×
869
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
870
                process_name = "unknown"
×
871
            logging.debug("Reaped Chrome process: PID %d (%s)", pid, process_name)
×
872
    except (ChildProcessError, OSError):
×
873
        # 子プロセスでない場合や既に回収済みの場合は無視
874
        pass
×
875

876

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

882

883
def _get_remaining_chrome_pids(chrome_pids: list[int]) -> list[int]:
1✔
884
    """指定されたPIDリストから、まだ生存しているChrome関連プロセスを取得"""
885
    remaining = []
×
886
    for pid in chrome_pids:
×
887
        try:
×
888
            if psutil.pid_exists(pid):
×
889
                process = psutil.Process(pid)
×
890
                if (
×
891
                    process.is_running()
892
                    and process.status() != psutil.STATUS_ZOMBIE
893
                    and _is_chrome_related_process(process)
894
                ):
895
                    remaining.append(pid)
×
896
        except (psutil.NoSuchProcess, psutil.AccessDenied):
×
897
            pass
×
898
    return remaining
×
899

900

901
def _wait_for_processes_with_check(
1✔
902
    chrome_pids: list[int],
903
    timeout: float,
904
    poll_interval: float = 0.2,
905
    log_interval: float = 1.0,
906
) -> list[int]:
907
    """プロセスの終了を待機しつつ、残存プロセスをチェック
908

909
    Args:
910
        chrome_pids: 監視対象のプロセスIDリスト
911
        timeout: 最大待機時間(秒)
912
        poll_interval: チェック間隔(秒)
913
        log_interval: ログ出力間隔(秒)
914

915
    Returns:
916
        タイムアウト後も残存しているプロセスIDのリスト
917

918
    """
919
    elapsed = 0.0
×
920
    last_log_time = 0.0
×
921
    remaining_pids = list(chrome_pids)
×
922

923
    while remaining_pids and elapsed < timeout:
×
924
        time.sleep(poll_interval)
×
925
        elapsed += poll_interval
×
926
        remaining_pids = _get_remaining_chrome_pids(remaining_pids)
×
927

928
        if remaining_pids and (elapsed - last_log_time) >= log_interval:
×
929
            logging.info(
×
930
                "Found %d remaining Chrome processes after %.0fs",
931
                len(remaining_pids),
932
                elapsed,
933
            )
934
            last_log_time = elapsed
×
935

936
    return remaining_pids
×
937

938

939
def quit_driver_gracefully(
1✔
940
    driver: WebDriver | None,
941
    wait_sec: float = 5.0,
942
    sigterm_wait_sec: float = 5.0,
943
    sigkill_wait_sec: float = 5.0,
944
) -> None:
945
    """Chrome WebDriverを確実に終了する
946

947
    終了フロー:
948
    1. driver.quit() を呼び出し
949
    2. wait_sec 秒待機しつつプロセス終了をチェック
950
    3. 残存プロセスがあれば SIGTERM を送信
951
    4. sigterm_wait_sec 秒待機しつつプロセス終了をチェック
952
    5. 残存プロセスがあれば SIGKILL を送信
953
    6. sigkill_wait_sec 秒待機
954

955
    Args:
956
        driver: 終了する WebDriver インスタンス
957
        wait_sec: quit 後にプロセス終了を待機する秒数(デフォルト: 5秒)
958
        sigterm_wait_sec: SIGTERM 後にプロセス終了を待機する秒数(デフォルト: 5秒)
959
        sigkill_wait_sec: SIGKILL 後にプロセス回収を待機する秒数(デフォルト: 5秒)
960

961
    """
962
    if driver is None:
1✔
963
        return
1✔
964

965
    # quit前にChrome関連プロセスを記録
966
    chrome_pids_before = _get_chrome_related_processes(driver)
1✔
967

968
    try:
1✔
969
        # WebDriverの正常終了を試行(これがタブのクローズも含む)
970
        driver.quit()
1✔
971
        logging.info("WebDriver quit successfully")
1✔
972
    except Exception:
1✔
973
        logging.warning("Failed to quit driver normally", exc_info=True)
1✔
974
    finally:
975
        # undetected_chromedriver の __del__ がシャットダウン時に再度呼ばれるのを防ぐ
976
        if hasattr(driver, "_has_quit"):
1✔
977
            driver._has_quit = True  # type: ignore[attr-defined]
1✔
978

979
    # ChromeDriverサービスの停止を試行
980
    try:
1✔
981
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "stop"):  # type: ignore[attr-defined]
1✔
982
            driver.service.stop()  # type: ignore[attr-defined]
×
983
    except (ConnectionResetError, OSError):
×
984
        # Chrome が既に終了している場合は無視
985
        logging.debug("Chrome service already stopped")
×
986
    except Exception:
×
987
        logging.warning("Failed to stop Chrome service", exc_info=True)
×
988

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

992
    if not remaining_pids:
1✔
993
        logging.debug("All Chrome processes exited normally")
1✔
994
        return
1✔
995

996
    # Step 2: 残存プロセスに SIGTERM を送信
997
    logging.info(
×
998
        "Found %d remaining Chrome processes after %.0fs, sending SIGTERM",
999
        len(remaining_pids),
1000
        wait_sec,
1001
    )
1002
    _send_signal_to_processes(remaining_pids, signal.SIGTERM, "SIGTERM")
×
1003

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

1007
    if not remaining_pids:
×
1008
        logging.info("All Chrome processes exited after SIGTERM")
×
1009
        _reap_chrome_processes(chrome_pids_before)
×
1010
        return
×
1011

1012
    # Step 4: 残存プロセスに SIGKILL を送信
1013
    logging.warning(
×
1014
        "Chrome processes still alive after SIGTERM + %.1fs, sending SIGKILL to %d processes",
1015
        sigterm_wait_sec,
1016
        len(remaining_pids),
1017
    )
1018
    _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1019

1020
    # Step 5: SIGKILL 後に sigkill_wait_sec 秒待機してプロセス回収
1021
    time.sleep(sigkill_wait_sec)
×
1022
    _reap_chrome_processes(chrome_pids_before)
×
1023

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

1027
    # 回収できなかったプロセスについて警告
1028
    if still_remaining:
×
1029
        for pid in still_remaining:
×
1030
            try:
×
1031
                process = psutil.Process(pid)
×
1032
                logging.warning("Failed to collect Chrome-related process: PID %d (%s)", pid, process.name())
×
1033
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1034
                pass
×
1035

1036

1037
if __name__ == "__main__":
1038
    import pathlib
1039

1040
    import docopt
1041
    import selenium.webdriver.support.wait
1042

1043
    import my_lib.config
1044
    import my_lib.logger
1045

1046
    assert __doc__ is not None  # noqa: S101
1047
    args = docopt.docopt(__doc__)
1048

1049
    config_file = args["-c"]
1050
    debug_mode = args["-D"]
1051

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

1054
    config = my_lib.config.load(config_file)
1055

1056
    driver = create_driver("test", pathlib.Path(config["data"]["selenium"]))
1057
    wait = selenium.webdriver.support.wait.WebDriverWait(driver, 5)
1058

1059
    driver.get("https://www.google.com/")
1060
    wait.until(
1061
        selenium.webdriver.support.expected_conditions.presence_of_element_located(
1062
            (selenium.webdriver.common.by.By.XPATH, '//input[contains(@value, "Google")]')
1063
        )
1064
    )
1065

1066
    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