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

kimata / my-py-lib / 20701874886

05 Jan 2026 12:53AM UTC coverage: 64.5% (-0.05%) from 64.546%
20701874886

push

github

kimata
feat: create_driver に use_undetected 引数を追加

- use_undetected=True(デフォルト): undetected_chromedriver を使用
- use_undetected=False: 通常の selenium.webdriver.Chrome を使用
- Chrome オプション作成を _create_chrome_options() に分離

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

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

2 of 19 new or added lines in 1 file covered. (10.53%)

2 existing lines in 1 file now uncovered.

3096 of 4800 relevant lines covered (64.5%)

0.65 hits per line

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

32.63
/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_chrome_options(
1✔
78
    profile_name: str,
79
    chrome_data_path: pathlib.Path,
80
    log_path: pathlib.Path,
81
    is_headless: bool,
82
) -> selenium.webdriver.chrome.options.Options:
83
    """Chrome オプションを作成する
84

85
    Args:
86
        profile_name: プロファイル名
87
        chrome_data_path: Chrome データディレクトリのパス
88
        log_path: ログディレクトリのパス
89
        is_headless: ヘッドレスモードで起動するか
90

91
    Returns:
92
        設定済みの Chrome オプション
93

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

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

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

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

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

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

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

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

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

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

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

NEW
126
    return options
×
127

128

129
def _create_driver_impl(
1✔
130
    profile_name: str,
131
    data_path: pathlib.Path,
132
    is_headless: bool,
133
    use_subprocess: bool,
134
    use_undetected: bool,
135
) -> WebDriver:
136
    """WebDriver を作成する内部実装
137

138
    Args:
139
        profile_name: プロファイル名
140
        data_path: データディレクトリのパス
141
        is_headless: ヘッドレスモードで起動するか
142
        use_subprocess: サブプロセスで Chrome を起動するか(undetected_chromedriver のみ)
143
        use_undetected: undetected_chromedriver を使用するか
144

145
    Returns:
146
        WebDriver インスタンス
147

148
    """
NEW
149
    chrome_data_path = data_path / "chrome"
×
NEW
150
    log_path = data_path / "log"
×
151

152
    # NOTE: Pytest を並列実行できるようにする
NEW
153
    suffix = os.environ.get("PYTEST_XDIST_WORKER", None)
×
NEW
154
    if suffix is not None:
×
NEW
155
        profile_name += "." + suffix
×
156

NEW
157
    chrome_data_path.mkdir(parents=True, exist_ok=True)
×
NEW
158
    log_path.mkdir(parents=True, exist_ok=True)
×
159

NEW
160
    options = _create_chrome_options(profile_name, chrome_data_path, log_path, is_headless)
×
161

UNCOV
162
    service = selenium.webdriver.chrome.service.Service(
×
163
        service_args=["--verbose", f"--log-path={str(log_path / 'webdriver.log')!s}"],
164
    )
165

NEW
166
    if use_undetected:
×
NEW
167
        chrome_version = _get_chrome_version()
×
168

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

NEW
174
        driver = undetected_chromedriver.Chrome(
×
175
            service=service,
176
            options=options,
177
            use_subprocess=use_subprocess,
178
            version_main=chrome_version,
179
            user_multi_procs=use_multi_procs,
180
        )
181
    else:
NEW
182
        driver = selenium.webdriver.Chrome(
×
183
            service=service,
184
            options=options,
185
        )
186

187
    driver.set_page_load_timeout(30)
×
188

189
    # CDP を使って日本語ロケールを強制設定
190
    set_japanese_locale(driver)
×
191

192
    return driver
×
193

194

195
def create_driver(
1✔
196
    profile_name: str,
197
    data_path: pathlib.Path,
198
    is_headless: bool = True,
199
    clean_profile: bool = False,
200
    auto_recover: bool = True,
201
    use_subprocess: bool = False,
202
    use_undetected: bool = True,
203
) -> WebDriver:
204
    """Chrome WebDriver を作成する
205

206
    Args:
207
        profile_name: プロファイル名
208
        data_path: データディレクトリのパス
209
        is_headless: ヘッドレスモードで起動するか
210
        clean_profile: 起動前にロックファイルを削除するか
211
        auto_recover: プロファイル破損時に自動リカバリするか
212
        use_subprocess: サブプロセスで Chrome を起動するか(undetected_chromedriver のみ)
213
        use_undetected: undetected_chromedriver を使用するか(デフォルト: True)
214

215
    """
216
    # NOTE: ルートロガーの出力レベルを変更した場合でも Selenium 関係は抑制する
217
    logging.getLogger("urllib3.connectionpool").setLevel(logging.WARNING)
×
218
    logging.getLogger("selenium.webdriver.common.selenium_manager").setLevel(logging.WARNING)
×
219
    logging.getLogger("selenium.webdriver.remote.remote_connection").setLevel(logging.WARNING)
×
220

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

225
    # プロファイル健全性チェック
226
    health = my_lib.chrome_util._check_profile_health(profile_path)
×
227
    if not health.is_healthy:
×
228
        logging.warning("Profile health check failed: %s", ", ".join(health.errors))
×
229

230
        if health.has_lock_files and not (health.has_corrupted_json or health.has_corrupted_db):
×
231
            # ロックファイルのみの問題なら削除して続行
232
            logging.info("Cleaning up lock files only")
×
233
            my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
234
        elif auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
235
            # JSON または DB が破損している場合はプロファイルをリカバリ
236
            logging.warning("Profile is corrupted, attempting recovery")
×
237
            if my_lib.chrome_util._recover_corrupted_profile(profile_path):
×
238
                logging.info("Profile recovery successful, will create new profile")
×
239
            else:
240
                logging.error("Profile recovery failed")
×
241

242
    if clean_profile:
×
243
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
244

245
    # NOTE: 1回だけ自動リトライ
246
    try:
×
NEW
247
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess, use_undetected)
×
248
    except Exception as e:
×
249
        logging.warning("First attempt to create driver failed: %s", e)
×
250

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

254
        # プロファイルのロックファイルを削除
255
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
256

257
        # 再度健全性チェック
258
        health = my_lib.chrome_util._check_profile_health(profile_path)
×
259
        if not health.is_healthy and auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
260
            logging.warning("Profile still corrupted after first attempt, recovering")
×
261
            my_lib.chrome_util._recover_corrupted_profile(profile_path)
×
262

NEW
263
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess, use_undetected)
×
264

265

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

269

270
def get_text(
1✔
271
    driver: WebDriver,
272
    xpath: str,
273
    safe_text: str,
274
    wait: WebDriverWait[WebDriver] | None = None,
275
) -> str:
276
    if wait is not None:
×
277
        wait.until(
×
278
            selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(
279
                (selenium.webdriver.common.by.By.XPATH, xpath)
280
            )
281
        )
282

283
    if len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0:
×
284
        return driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).text.strip()
×
285
    else:
286
        return safe_text
×
287

288

289
def input_xpath(
1✔
290
    driver: WebDriver,
291
    xpath: str,
292
    text: str,
293
    wait: WebDriverWait[WebDriver] | None = None,
294
    is_warn: bool = True,
295
) -> bool:
296
    if wait is not None:
×
297
        wait.until(
×
298
            selenium.webdriver.support.expected_conditions.element_to_be_clickable(
299
                (selenium.webdriver.common.by.By.XPATH, xpath)
300
            )
301
        )
302
        time.sleep(0.05)
×
303

304
    if xpath_exists(driver, xpath):
×
305
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).send_keys(text)
×
306
        return True
×
307
    else:
308
        if is_warn:
×
309
            logging.warning("Element is not found: %s", xpath)
×
310
        return False
×
311

312

313
def click_xpath(
1✔
314
    driver: WebDriver,
315
    xpath: str,
316
    wait: WebDriverWait[WebDriver] | None = None,
317
    is_warn: bool = True,
318
    move: bool = False,
319
) -> bool:
320
    if wait is not None:
×
321
        wait.until(
×
322
            selenium.webdriver.support.expected_conditions.element_to_be_clickable(
323
                (selenium.webdriver.common.by.By.XPATH, xpath)
324
            )
325
        )
326
        time.sleep(0.05)
×
327

328
    if xpath_exists(driver, xpath):
×
329
        elem = driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath)
×
330
        if move:
×
331
            action = selenium.webdriver.common.action_chains.ActionChains(driver)
×
332
            action.move_to_element(elem)
×
333
            action.perform()
×
334

335
        elem.click()
×
336
        return True
×
337
    else:
338
        if is_warn:
×
339
            logging.warning("Element is not found: %s", xpath)
×
340
        return False
×
341

342

343
def is_display(driver: WebDriver, xpath: str) -> bool:
1✔
344
    return (len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0) and (
×
345
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).is_displayed()
346
    )
347

348

349
def random_sleep(sec: float) -> None:
1✔
350
    RATIO = 0.8
1✔
351

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

354

355
def with_retry(
1✔
356
    func: Callable[[], T],
357
    max_retries: int = 3,
358
    delay: float = 1.0,
359
    exceptions: tuple[type[Exception], ...] = (Exception,),
360
    on_retry: Callable[[int, Exception], bool | None] | None = None,
361
) -> T:
362
    """リトライ付きで関数を実行
363

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

367
    Args:
368
        func: 実行する関数
369
        max_retries: 最大リトライ回数
370
        delay: リトライ間の待機秒数
371
        exceptions: リトライ対象の例外タプル
372
        on_retry: リトライ時のコールバック (attempt, exception)
373
            - None または True を返すとリトライを継続
374
            - False を返すとリトライを中止して例外を再スロー
375

376
    Returns:
377
        成功時は関数の戻り値
378

379
    Raises:
380
        最後の例外を再スロー
381

382
    """
383
    last_exception: Exception | None = None
×
384

385
    for attempt in range(max_retries):
×
386
        try:
×
387
            return func()
×
388
        except exceptions as e:
×
389
            last_exception = e
×
390
            if attempt < max_retries - 1:
×
391
                if on_retry:
×
392
                    should_continue = on_retry(attempt + 1, e)
×
393
                    if should_continue is False:
×
394
                        raise
×
395
                time.sleep(delay)
×
396

397
    if last_exception:
×
398
        raise last_exception
×
399
    raise RuntimeError("Unexpected state in with_retry")
×
400

401

402
def wait_patiently(
1✔
403
    driver: WebDriver,
404
    wait: WebDriverWait[WebDriver],
405
    target: Any,
406
) -> None:
407
    error: selenium.common.exceptions.TimeoutException | None = None
×
408
    for i in range(WAIT_RETRY_COUNT + 1):
×
409
        try:
×
410
            wait.until(target)
×
411
            return
×
412
        except selenium.common.exceptions.TimeoutException as e:
×
413
            logging.warning(
×
414
                "タイムアウトが発生しました。(%s in %s line %d)",
415
                inspect.stack()[1].function,
416
                inspect.stack()[1].filename,
417
                inspect.stack()[1].lineno,
418
            )
419
            error = e
×
420

421
            logging.info(i)
×
422
            if i != WAIT_RETRY_COUNT:
×
423
                logging.info("refresh")
×
424
                driver.refresh()
×
425

426
    if error is not None:
×
427
        raise error
×
428

429

430
def dump_page(
1✔
431
    driver: WebDriver,
432
    index: int,
433
    dump_path: pathlib.Path,
434
    stack_index: int = 1,
435
) -> None:
436
    name = inspect.stack()[stack_index].function.replace("<", "").replace(">", "")
×
437

438
    dump_path.mkdir(parents=True, exist_ok=True)
×
439

440
    png_path = dump_path / f"{name}_{index:02d}.png"
×
441
    htm_path = dump_path / f"{name}_{index:02d}.htm"
×
442

443
    driver.save_screenshot(str(png_path))
×
444

445
    with htm_path.open("w", encoding="utf-8") as f:
×
446
        f.write(driver.page_source)
×
447

448
    logging.info(
×
449
        "page dump: %02d from %s in %s line %d",
450
        index,
451
        inspect.stack()[stack_index].function,
452
        inspect.stack()[stack_index].filename,
453
        inspect.stack()[stack_index].lineno,
454
    )
455

456

457
def clear_cache(driver: WebDriver) -> None:
1✔
458
    driver.execute_cdp_cmd("Network.clearBrowserCache", {})
×
459

460

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

464
    Chrome の起動オプションだけでは言語設定が変わってしまうことがあるため、
465
    CDP を使って Accept-Language ヘッダーとロケールを強制的に日本語に設定する。
466
    """
467
    try:
×
468
        # NOTE: Network.setExtraHTTPHeaders は Network.enable を先に呼ばないと機能しない
469
        driver.execute_cdp_cmd("Network.enable", {})
×
470
        driver.execute_cdp_cmd(
×
471
            "Network.setExtraHTTPHeaders",
472
            {"headers": {"Accept-Language": "ja-JP,ja;q=0.9"}},
473
        )
474
        driver.execute_cdp_cmd(
×
475
            "Emulation.setLocaleOverride",
476
            {"locale": "ja-JP"},
477
        )
478
        logging.debug("Japanese locale set via CDP")
×
479
    except Exception:
×
480
        logging.warning("Failed to set Japanese locale via CDP")
×
481

482

483
def clean_dump(dump_path: pathlib.Path, keep_days: int = 1) -> None:
1✔
484
    if not dump_path.exists():
1✔
485
        return
1✔
486

487
    time_threshold = datetime.timedelta(keep_days)
1✔
488

489
    for item in dump_path.iterdir():
1✔
490
        if not item.is_file():
1✔
491
            continue
1✔
492
        try:
1✔
493
            time_diff = datetime.datetime.now(datetime.UTC) - datetime.datetime.fromtimestamp(
1✔
494
                item.stat().st_mtime, datetime.UTC
495
            )
496
        except FileNotFoundError:
×
497
            # ファイルが別プロセスにより削除された場合(SQLiteの一時ファイルなど)
498
            continue
×
499
        if time_diff > time_threshold:
1✔
500
            logging.warning("remove %s [%s day(s) old].", item.absolute(), f"{time_diff.days:,}")
1✔
501

502
            item.unlink(missing_ok=True)
1✔
503

504

505
def get_memory_info(driver: WebDriver) -> dict[str, Any]:
1✔
506
    """ブラウザのメモリ使用量を取得(単位: KB)"""
507
    total_bytes = subprocess.Popen(  # noqa: S602
×
508
        "smem -t -c pss -P chrome | tail -n 1",  # noqa: S607
509
        shell=True,
510
        stdout=subprocess.PIPE,
511
    ).communicate()[0]
512
    total = int(str(total_bytes, "utf-8").strip())  # smem の出力は KB 単位
×
513

514
    try:
×
515
        memory_info = driver.execute_cdp_cmd("Memory.getAllTimeSamplingProfile", {})
×
516
        heap_usage = driver.execute_cdp_cmd("Runtime.getHeapUsage", {})
×
517

518
        heap_used = heap_usage.get("usedSize", 0) // 1024  # bytes → KB
×
519
        heap_total = heap_usage.get("totalSize", 0) // 1024  # bytes → KB
×
520
    except Exception as e:
×
521
        logging.debug("Failed to get memory usage: %s", e)
×
522

523
        memory_info = None
×
524
        heap_used = 0
×
525
        heap_total = 0
×
526

527
    return {
×
528
        "total": total,
529
        "heap_used": heap_used,
530
        "heap_total": heap_total,
531
        "memory_info": memory_info,
532
    }
533

534

535
def log_memory_usage(driver: WebDriver) -> None:
1✔
536
    mem_info = get_memory_info(driver)
×
537
    logging.info(
×
538
        "Chrome memory: %s MB (JS heap: %s MB)",
539
        f"""{mem_info["total"] // 1024:,}""",
540
        f"""{mem_info["heap_used"] // 1024:,}""",
541
    )
542

543

544
def _warmup(
1✔
545
    driver: WebDriver,
546
    keyword: str,
547
    url_pattern: str,
548
    sleep_sec: int = 3,
549
) -> None:
550
    # NOTE: ダミーアクセスを行って BOT ではないと思わせる。(効果なさそう...)
551
    driver.get("https://www.yahoo.co.jp/")
×
552
    time.sleep(sleep_sec)
×
553

554
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(keyword)
×
555
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(
×
556
        selenium.webdriver.common.keys.Keys.ENTER
557
    )
558

559
    time.sleep(sleep_sec)
×
560

561
    driver.find_element(
×
562
        selenium.webdriver.common.by.By.XPATH, f'//a[contains(@href, "{url_pattern}")]'
563
    ).click()
564

565
    time.sleep(sleep_sec)
×
566

567

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

571
    def __init__(self, driver: WebDriver, url: str) -> None:
1✔
572
        """初期化
573

574
        Args:
575
            driver: WebDriver インスタンス
576
            url: 開く URL
577

578
        """
579
        self.driver = driver
1✔
580
        self.url = url
1✔
581
        self.original_window: str | None = None
1✔
582

583
    def __enter__(self) -> None:
1✔
584
        """新しいタブを開いて URL にアクセス"""
585
        self.original_window = self.driver.current_window_handle
1✔
586
        self.driver.execute_script("window.open('');")
1✔
587
        self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
588
        try:
1✔
589
            self.driver.get(self.url)
1✔
590
        except Exception:
×
591
            # NOTE: URL読み込みに失敗した場合もクリーンアップしてから例外を再送出
592
            self._cleanup()
×
593
            raise
×
594

595
    def _cleanup(self) -> None:
1✔
596
        """タブを閉じて元のウィンドウに戻る"""
597
        try:
1✔
598
            # 余分なタブを閉じる
599
            while len(self.driver.window_handles) > 1:
1✔
600
                self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
601
                self.driver.close()
1✔
602
            if self.original_window is not None:
1✔
603
                self.driver.switch_to.window(self.original_window)
1✔
604
            time.sleep(0.1)
1✔
605
        except Exception:
1✔
606
            # NOTE: Chromeがクラッシュした場合は無視(既に終了しているため操作不可)
607
            logging.exception("タブのクリーンアップに失敗しました(Chromeがクラッシュした可能性があります)")
1✔
608

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

615
            # about:blank に移動してレンダラーの状態をリセット
616
            self.driver.get("about:blank")
×
617
            time.sleep(0.5)
×
618
        except Exception:
×
619
            logging.warning("ブラウザの回復に失敗しました")
×
620

621
    def __exit__(
1✔
622
        self,
623
        exception_type: type[BaseException] | None,
624
        exception_value: BaseException | None,
625
        traceback: types.TracebackType | None,
626
    ) -> None:
627
        """タブを閉じて元のウィンドウに戻る"""
628
        self._cleanup()
1✔
629

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

634

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

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

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

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

651
    Examples:
652
        基本的な使用方法::
653

654
            with my_lib.selenium_util.error_handler(driver, message="ログイン処理に失敗") as handler:
655
                driver.get(login_url)
656
                driver.find_element(...).click()
657

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

660
            def notify(exc, screenshot):
661
                slack.error("エラー発生", str(exc), screenshot)
662

663
            with my_lib.selenium_util.error_handler(
664
                driver,
665
                message="クロール処理に失敗",
666
                on_error=notify,
667
            ):
668
                crawl_page(driver)
669

670
        例外を抑制して続行::
671

672
            with my_lib.selenium_util.error_handler(driver, reraise=False) as handler:
673
                risky_operation()
674

675
            if handler.exception:
676
                logging.warning("処理をスキップしました")
677

678
    """
679

680
    def __init__(
1✔
681
        self,
682
        driver: WebDriver,
683
        message: str = "Selenium operation failed",
684
        on_error: Callable[[Exception, PIL.Image.Image | None], None] | None = None,
685
        capture_screenshot: bool = True,
686
        reraise: bool = True,
687
    ) -> None:
688
        """初期化"""
689
        self.driver = driver
1✔
690
        self.message = message
1✔
691
        self.on_error = on_error
1✔
692
        self.capture_screenshot = capture_screenshot
1✔
693
        self.reraise = reraise
1✔
694
        self.exception: Exception | None = None
1✔
695
        self.screenshot: PIL.Image.Image | None = None
1✔
696

697
    def __enter__(self) -> Self:
1✔
698
        """コンテキストマネージャの開始"""
699
        return self
1✔
700

701
    def __exit__(
1✔
702
        self,
703
        exception_type: type[BaseException] | None,
704
        exception_value: BaseException | None,
705
        traceback: types.TracebackType | None,
706
    ) -> bool:
707
        """コンテキストマネージャの終了、エラー処理を実行"""
708
        if exception_value is None:
1✔
709
            return False
1✔
710

711
        # 例外を記録
712
        if isinstance(exception_value, Exception):
1✔
713
            self.exception = exception_value
1✔
714
        else:
715
            # BaseException(KeyboardInterrupt など)は処理せず再送出
716
            return False
×
717

718
        # ログ出力
719
        logging.exception(self.message)
1✔
720

721
        # スクリーンショット取得
722
        if self.capture_screenshot:
1✔
723
            try:
1✔
724
                screenshot_bytes = self.driver.get_screenshot_as_png()
1✔
725
                self.screenshot = PIL.Image.open(io.BytesIO(screenshot_bytes))
1✔
726
            except Exception:
1✔
727
                logging.debug("Failed to capture screenshot for error handling")
1✔
728

729
        # コールバック呼び出し
730
        if self.on_error is not None:
1✔
731
            try:
1✔
732
                self.on_error(self.exception, self.screenshot)
1✔
733
            except Exception:
×
734
                logging.exception("Error in on_error callback")
×
735

736
        # reraise=False なら例外を抑制
737
        return not self.reraise
1✔
738

739

740
def _is_chrome_related_process(process: psutil.Process) -> bool:
1✔
741
    """プロセスがChrome関連かどうかを判定"""
742
    try:
1✔
743
        process_name = process.name().lower()
1✔
744
        # Chrome関連のプロセス名パターン
745
        chrome_patterns = ["chrome", "chromium", "google-chrome", "undetected_chro"]
1✔
746
        # chromedriverは除外
747
        if "chromedriver" in process_name:
1✔
748
            return False
1✔
749
        return any(pattern in process_name for pattern in chrome_patterns)
1✔
750
    except (psutil.NoSuchProcess, psutil.AccessDenied):
1✔
751
        return False
1✔
752

753

754
def _get_chrome_processes_by_pgid(chromedriver_pid: int, existing_pids: set[int]) -> list[int]:
1✔
755
    """プロセスグループIDで追加のChrome関連プロセスを取得"""
756
    additional_pids = []
×
757
    try:
×
758
        pgid = os.getpgid(chromedriver_pid)
×
759
        for proc in psutil.process_iter(["pid", "name", "ppid"]):
×
760
            if proc.info["pid"] in existing_pids:
×
761
                continue
×
762
            try:
×
763
                if os.getpgid(proc.info["pid"]) == pgid:
×
764
                    proc_obj = psutil.Process(proc.info["pid"])
×
765
                    if _is_chrome_related_process(proc_obj):
×
766
                        additional_pids.append(proc.info["pid"])
×
767
                        logging.debug(
×
768
                            "Found Chrome-related process by pgid: PID %d, name: %s",
769
                            proc.info["pid"],
770
                            proc.info["name"],
771
                        )
772
            except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
×
773
                pass
×
774
    except (OSError, psutil.NoSuchProcess):
×
775
        logging.debug("Failed to get process group ID for chromedriver")
×
776
    return additional_pids
×
777

778

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

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

787
    # 1. driver.service.process の子プロセスを検索
788
    try:
×
789
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "process"):  # type: ignore[attr-defined]
×
790
            process = driver.service.process  # type: ignore[attr-defined]
×
791
            if process and hasattr(process, "pid"):
×
792
                chromedriver_pid = process.pid
×
793

794
                # psutilでプロセス階層を取得
795
                parent_process = psutil.Process(chromedriver_pid)
×
796
                children = parent_process.children(recursive=True)
×
797

798
                for child in children:
×
799
                    chrome_pids.add(child.pid)
×
800
                    logging.debug(
×
801
                        "Found Chrome-related process (service child): PID %d, name: %s",
802
                        child.pid,
803
                        child.name(),
804
                    )
805
    except Exception:
×
806
        logging.exception("Failed to get Chrome-related processes from service")
×
807

808
    # 2. 現在の Python プロセスの全子孫から Chrome 関連プロセスを検索
809
    try:
×
810
        current_process = psutil.Process()
×
811
        all_children = current_process.children(recursive=True)
×
812

813
        for child in all_children:
×
814
            if child.pid in chrome_pids:
×
815
                continue
×
816
            try:
×
817
                if _is_chrome_related_process(child):
×
818
                    chrome_pids.add(child.pid)
×
819
                    logging.debug(
×
820
                        "Found Chrome-related process (python child): PID %d, name: %s",
821
                        child.pid,
822
                        child.name(),
823
                    )
824
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
825
                pass
×
826
    except Exception:
×
827
        logging.exception("Failed to get Chrome-related processes from python children")
×
828

829
    return list(chrome_pids)
×
830

831

832
def _send_signal_to_processes(pids: list[int], sig: signal.Signals, signal_name: str) -> None:
1✔
833
    """プロセスリストに指定されたシグナルを送信"""
834
    errors = []
×
835
    for pid in pids:
×
836
        try:
×
837
            # プロセス名を取得
838
            try:
×
839
                process = psutil.Process(pid)
×
840
                process_name = process.name()
×
841
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
842
                process_name = "unknown"
×
843

844
            if sig == signal.SIGKILL:
×
845
                # プロセスがまだ存在するかチェック
846
                os.kill(pid, 0)  # シグナル0は存在確認
×
847
            os.kill(pid, sig)
×
848
            logging.info("Sent %s to process: PID %d (%s)", signal_name, pid, process_name)
×
849
        except (ProcessLookupError, OSError) as e:
×
850
            # プロセスが既に終了している場合は無視
851
            errors.append((pid, e))
×
852

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

857

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

861
    Args:
862
        chrome_pids: 終了対象のプロセスIDリスト
863
        timeout: SIGTERM後にプロセス終了を待機する最大時間(秒)
864

865
    """
866
    if not chrome_pids:
×
867
        return
×
868

869
    # 優雅な終了(SIGTERM)
870
    _send_signal_to_processes(chrome_pids, signal.SIGTERM, "SIGTERM")
×
871

872
    # プロセスの終了を待機(ポーリング)
873
    remaining_pids = list(chrome_pids)
×
874
    poll_interval = 0.2
×
875
    elapsed = 0.0
×
876

877
    while remaining_pids and elapsed < timeout:
×
878
        time.sleep(poll_interval)
×
879
        elapsed += poll_interval
×
880

881
        # まだ生存しているプロセスをチェック
882
        still_alive = []
×
883
        for pid in remaining_pids:
×
884
            try:
×
885
                if psutil.pid_exists(pid):
×
886
                    process = psutil.Process(pid)
×
887
                    if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
×
888
                        still_alive.append(pid)
×
889
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
890
                pass
×
891

892
        remaining_pids = still_alive
×
893

894
    # タイムアウト後もまだ残っているプロセスにのみ SIGKILL を送信
895
    if remaining_pids:
×
896
        logging.warning(
×
897
            "Chrome processes still alive after %.1fs, sending SIGKILL to %d processes",
898
            elapsed,
899
            len(remaining_pids),
900
        )
901
        _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
902

903

904
def _reap_single_process(pid: int) -> None:
1✔
905
    """単一プロセスをwaitpidで回収"""
906
    try:
×
907
        # ノンブロッキングでwaitpid
908
        result_pid, status = os.waitpid(pid, os.WNOHANG)
×
909
        if result_pid == pid:
×
910
            # プロセス名を取得
911
            try:
×
912
                process = psutil.Process(pid)
×
913
                process_name = process.name()
×
914
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
915
                process_name = "unknown"
×
916
            logging.debug("Reaped Chrome process: PID %d (%s)", pid, process_name)
×
917
    except (ChildProcessError, OSError):
×
918
        # 子プロセスでない場合や既に回収済みの場合は無視
919
        pass
×
920

921

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

927

928
def _get_remaining_chrome_pids(chrome_pids: list[int]) -> list[int]:
1✔
929
    """指定されたPIDリストから、まだ生存しているChrome関連プロセスを取得"""
930
    remaining = []
×
931
    for pid in chrome_pids:
×
932
        try:
×
933
            if psutil.pid_exists(pid):
×
934
                process = psutil.Process(pid)
×
935
                if (
×
936
                    process.is_running()
937
                    and process.status() != psutil.STATUS_ZOMBIE
938
                    and _is_chrome_related_process(process)
939
                ):
940
                    remaining.append(pid)
×
941
        except (psutil.NoSuchProcess, psutil.AccessDenied):
×
942
            pass
×
943
    return remaining
×
944

945

946
def _wait_for_processes_with_check(
1✔
947
    chrome_pids: list[int],
948
    timeout: float,
949
    poll_interval: float = 0.2,
950
    log_interval: float = 1.0,
951
) -> list[int]:
952
    """プロセスの終了を待機しつつ、残存プロセスをチェック
953

954
    Args:
955
        chrome_pids: 監視対象のプロセスIDリスト
956
        timeout: 最大待機時間(秒)
957
        poll_interval: チェック間隔(秒)
958
        log_interval: ログ出力間隔(秒)
959

960
    Returns:
961
        タイムアウト後も残存しているプロセスIDのリスト
962

963
    """
964
    elapsed = 0.0
×
965
    last_log_time = 0.0
×
966
    remaining_pids = list(chrome_pids)
×
967

968
    while remaining_pids and elapsed < timeout:
×
969
        time.sleep(poll_interval)
×
970
        elapsed += poll_interval
×
971
        remaining_pids = _get_remaining_chrome_pids(remaining_pids)
×
972

973
        if remaining_pids and (elapsed - last_log_time) >= log_interval:
×
974
            logging.info(
×
975
                "Found %d remaining Chrome processes after %.0fs",
976
                len(remaining_pids),
977
                elapsed,
978
            )
979
            last_log_time = elapsed
×
980

981
    return remaining_pids
×
982

983

984
def quit_driver_gracefully(
1✔
985
    driver: WebDriver | None,
986
    wait_sec: float = 5.0,
987
    sigterm_wait_sec: float = 5.0,
988
    sigkill_wait_sec: float = 5.0,
989
) -> None:
990
    """Chrome WebDriverを確実に終了する
991

992
    終了フロー:
993
    1. driver.quit() を呼び出し
994
    2. wait_sec 秒待機しつつプロセス終了をチェック
995
    3. 残存プロセスがあれば SIGTERM を送信
996
    4. sigterm_wait_sec 秒待機しつつプロセス終了をチェック
997
    5. 残存プロセスがあれば SIGKILL を送信
998
    6. sigkill_wait_sec 秒待機
999

1000
    Args:
1001
        driver: 終了する WebDriver インスタンス
1002
        wait_sec: quit 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1003
        sigterm_wait_sec: SIGTERM 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1004
        sigkill_wait_sec: SIGKILL 後にプロセス回収を待機する秒数(デフォルト: 5秒)
1005

1006
    """
1007
    if driver is None:
1✔
1008
        return
1✔
1009

1010
    # quit前にChrome関連プロセスを記録
1011
    chrome_pids_before = _get_chrome_related_processes(driver)
1✔
1012

1013
    try:
1✔
1014
        # WebDriverの正常終了を試行(これがタブのクローズも含む)
1015
        driver.quit()
1✔
1016
        logging.info("WebDriver quit successfully")
1✔
1017
    except Exception:
1✔
1018
        logging.warning("Failed to quit driver normally", exc_info=True)
1✔
1019
    finally:
1020
        # undetected_chromedriver の __del__ がシャットダウン時に再度呼ばれるのを防ぐ
1021
        if hasattr(driver, "_has_quit"):
1✔
1022
            driver._has_quit = True  # type: ignore[attr-defined]
1✔
1023

1024
    # ChromeDriverサービスの停止を試行
1025
    try:
1✔
1026
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "stop"):  # type: ignore[attr-defined]
1✔
1027
            driver.service.stop()  # type: ignore[attr-defined]
×
1028
    except (ConnectionResetError, OSError):
×
1029
        # Chrome が既に終了している場合は無視
1030
        logging.debug("Chrome service already stopped")
×
1031
    except Exception:
×
1032
        logging.warning("Failed to stop Chrome service", exc_info=True)
×
1033

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

1037
    if not remaining_pids:
1✔
1038
        logging.debug("All Chrome processes exited normally")
1✔
1039
        return
1✔
1040

1041
    # Step 2: 残存プロセスに SIGTERM を送信
1042
    logging.info(
×
1043
        "Found %d remaining Chrome processes after %.0fs, sending SIGTERM",
1044
        len(remaining_pids),
1045
        wait_sec,
1046
    )
1047
    _send_signal_to_processes(remaining_pids, signal.SIGTERM, "SIGTERM")
×
1048

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

1052
    if not remaining_pids:
×
1053
        logging.info("All Chrome processes exited after SIGTERM")
×
1054
        _reap_chrome_processes(chrome_pids_before)
×
1055
        return
×
1056

1057
    # Step 4: 残存プロセスに SIGKILL を送信
1058
    logging.warning(
×
1059
        "Chrome processes still alive after SIGTERM + %.1fs, sending SIGKILL to %d processes",
1060
        sigterm_wait_sec,
1061
        len(remaining_pids),
1062
    )
1063
    _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1064

1065
    # Step 5: SIGKILL 後に sigkill_wait_sec 秒待機してプロセス回収
1066
    time.sleep(sigkill_wait_sec)
×
1067
    _reap_chrome_processes(chrome_pids_before)
×
1068

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

1072
    # 回収できなかったプロセスについて警告
1073
    if still_remaining:
×
1074
        for pid in still_remaining:
×
1075
            try:
×
1076
                process = psutil.Process(pid)
×
1077
                logging.warning("Failed to collect Chrome-related process: PID %d (%s)", pid, process.name())
×
1078
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1079
                pass
×
1080

1081

1082
if __name__ == "__main__":
1083
    import pathlib
1084

1085
    import docopt
1086
    import selenium.webdriver.support.wait
1087

1088
    import my_lib.config
1089
    import my_lib.logger
1090

1091
    assert __doc__ is not None  # noqa: S101
1092
    args = docopt.docopt(__doc__)
1093

1094
    config_file = args["-c"]
1095
    debug_mode = args["-D"]
1096

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

1099
    config = my_lib.config.load(config_file)
1100

1101
    driver = create_driver("test", pathlib.Path(config["data"]["selenium"]))
1102
    wait = selenium.webdriver.support.wait.WebDriverWait(driver, 5)
1103

1104
    driver.get("https://www.google.com/")
1105
    wait.until(
1106
        selenium.webdriver.support.expected_conditions.presence_of_element_located(
1107
            (selenium.webdriver.common.by.By.XPATH, '//input[contains(@value, "Google")]')
1108
        )
1109
    )
1110

1111
    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