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

kimata / my-py-lib / 20702256026

05 Jan 2026 01:16AM UTC coverage: 64.473% (-0.03%) from 64.5%
20702256026

push

github

kimata
refactor: create_driver の引数順序を変更し不正な組み合わせを検出

- use_undetected を use_subprocess より前に移動
- use_undetected=False かつ use_subprocess=True の場合に ValueError を発生

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

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

0 of 2 new or added lines in 1 file covered. (0.0%)

3096 of 4802 relevant lines covered (64.47%)

0.64 hits per line

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

32.49
/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
    """
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

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
    """
149
    chrome_data_path = data_path / "chrome"
×
150
    log_path = data_path / "log"
×
151

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

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

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

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

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

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

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:
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_undetected: bool = True,
202
    use_subprocess: bool = False,
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_undetected: undetected_chromedriver を使用するか(デフォルト: True)
213
        use_subprocess: サブプロセスで Chrome を起動するか(undetected_chromedriver のみ)
214

215
    Raises:
216
        ValueError: use_undetected=False かつ use_subprocess=True の場合
217

218
    """
NEW
219
    if not use_undetected and use_subprocess:
×
NEW
220
        raise ValueError("use_subprocess=True は use_undetected=True の場合のみ有効です")
×
221

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

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

231
    # プロファイル健全性チェック
232
    health = my_lib.chrome_util._check_profile_health(profile_path)
×
233
    if not health.is_healthy:
×
234
        logging.warning("Profile health check failed: %s", ", ".join(health.errors))
×
235

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

248
    if clean_profile:
×
249
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
250

251
    # NOTE: 1回だけ自動リトライ
252
    try:
×
253
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess, use_undetected)
×
254
    except Exception as e:
×
255
        logging.warning("First attempt to create driver failed: %s", e)
×
256

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

260
        # プロファイルのロックファイルを削除
261
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
262

263
        # 再度健全性チェック
264
        health = my_lib.chrome_util._check_profile_health(profile_path)
×
265
        if not health.is_healthy and auto_recover and (health.has_corrupted_json or health.has_corrupted_db):
×
266
            logging.warning("Profile still corrupted after first attempt, recovering")
×
267
            my_lib.chrome_util._recover_corrupted_profile(profile_path)
×
268

269
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess, use_undetected)
×
270

271

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

275

276
def get_text(
1✔
277
    driver: WebDriver,
278
    xpath: str,
279
    safe_text: str,
280
    wait: WebDriverWait[WebDriver] | None = None,
281
) -> str:
282
    if wait is not None:
×
283
        wait.until(
×
284
            selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(
285
                (selenium.webdriver.common.by.By.XPATH, xpath)
286
            )
287
        )
288

289
    if len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0:
×
290
        return driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).text.strip()
×
291
    else:
292
        return safe_text
×
293

294

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

310
    if xpath_exists(driver, xpath):
×
311
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).send_keys(text)
×
312
        return True
×
313
    else:
314
        if is_warn:
×
315
            logging.warning("Element is not found: %s", xpath)
×
316
        return False
×
317

318

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

334
    if xpath_exists(driver, xpath):
×
335
        elem = driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath)
×
336
        if move:
×
337
            action = selenium.webdriver.common.action_chains.ActionChains(driver)
×
338
            action.move_to_element(elem)
×
339
            action.perform()
×
340

341
        elem.click()
×
342
        return True
×
343
    else:
344
        if is_warn:
×
345
            logging.warning("Element is not found: %s", xpath)
×
346
        return False
×
347

348

349
def is_display(driver: WebDriver, xpath: str) -> bool:
1✔
350
    return (len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0) and (
×
351
        driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).is_displayed()
352
    )
353

354

355
def random_sleep(sec: float) -> None:
1✔
356
    RATIO = 0.8
1✔
357

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

360

361
def with_retry(
1✔
362
    func: Callable[[], T],
363
    max_retries: int = 3,
364
    delay: float = 1.0,
365
    exceptions: tuple[type[Exception], ...] = (Exception,),
366
    on_retry: Callable[[int, Exception], bool | None] | None = None,
367
) -> T:
368
    """リトライ付きで関数を実行
369

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

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

382
    Returns:
383
        成功時は関数の戻り値
384

385
    Raises:
386
        最後の例外を再スロー
387

388
    """
389
    last_exception: Exception | None = None
×
390

391
    for attempt in range(max_retries):
×
392
        try:
×
393
            return func()
×
394
        except exceptions as e:
×
395
            last_exception = e
×
396
            if attempt < max_retries - 1:
×
397
                if on_retry:
×
398
                    should_continue = on_retry(attempt + 1, e)
×
399
                    if should_continue is False:
×
400
                        raise
×
401
                time.sleep(delay)
×
402

403
    if last_exception:
×
404
        raise last_exception
×
405
    raise RuntimeError("Unexpected state in with_retry")
×
406

407

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

427
            logging.info(i)
×
428
            if i != WAIT_RETRY_COUNT:
×
429
                logging.info("refresh")
×
430
                driver.refresh()
×
431

432
    if error is not None:
×
433
        raise error
×
434

435

436
def dump_page(
1✔
437
    driver: WebDriver,
438
    index: int,
439
    dump_path: pathlib.Path,
440
    stack_index: int = 1,
441
) -> None:
442
    name = inspect.stack()[stack_index].function.replace("<", "").replace(">", "")
×
443

444
    dump_path.mkdir(parents=True, exist_ok=True)
×
445

446
    png_path = dump_path / f"{name}_{index:02d}.png"
×
447
    htm_path = dump_path / f"{name}_{index:02d}.htm"
×
448

449
    driver.save_screenshot(str(png_path))
×
450

451
    with htm_path.open("w", encoding="utf-8") as f:
×
452
        f.write(driver.page_source)
×
453

454
    logging.info(
×
455
        "page dump: %02d from %s in %s line %d",
456
        index,
457
        inspect.stack()[stack_index].function,
458
        inspect.stack()[stack_index].filename,
459
        inspect.stack()[stack_index].lineno,
460
    )
461

462

463
def clear_cache(driver: WebDriver) -> None:
1✔
464
    driver.execute_cdp_cmd("Network.clearBrowserCache", {})
×
465

466

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

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

488

489
def clean_dump(dump_path: pathlib.Path, keep_days: int = 1) -> None:
1✔
490
    if not dump_path.exists():
1✔
491
        return
1✔
492

493
    time_threshold = datetime.timedelta(keep_days)
1✔
494

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

508
            item.unlink(missing_ok=True)
1✔
509

510

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

520
    try:
×
521
        memory_info = driver.execute_cdp_cmd("Memory.getAllTimeSamplingProfile", {})
×
522
        heap_usage = driver.execute_cdp_cmd("Runtime.getHeapUsage", {})
×
523

524
        heap_used = heap_usage.get("usedSize", 0) // 1024  # bytes → KB
×
525
        heap_total = heap_usage.get("totalSize", 0) // 1024  # bytes → KB
×
526
    except Exception as e:
×
527
        logging.debug("Failed to get memory usage: %s", e)
×
528

529
        memory_info = None
×
530
        heap_used = 0
×
531
        heap_total = 0
×
532

533
    return {
×
534
        "total": total,
535
        "heap_used": heap_used,
536
        "heap_total": heap_total,
537
        "memory_info": memory_info,
538
    }
539

540

541
def log_memory_usage(driver: WebDriver) -> None:
1✔
542
    mem_info = get_memory_info(driver)
×
543
    logging.info(
×
544
        "Chrome memory: %s MB (JS heap: %s MB)",
545
        f"""{mem_info["total"] // 1024:,}""",
546
        f"""{mem_info["heap_used"] // 1024:,}""",
547
    )
548

549

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

560
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(keyword)
×
561
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(
×
562
        selenium.webdriver.common.keys.Keys.ENTER
563
    )
564

565
    time.sleep(sleep_sec)
×
566

567
    driver.find_element(
×
568
        selenium.webdriver.common.by.By.XPATH, f'//a[contains(@href, "{url_pattern}")]'
569
    ).click()
570

571
    time.sleep(sleep_sec)
×
572

573

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

577
    def __init__(self, driver: WebDriver, url: str) -> None:
1✔
578
        """初期化
579

580
        Args:
581
            driver: WebDriver インスタンス
582
            url: 開く URL
583

584
        """
585
        self.driver = driver
1✔
586
        self.url = url
1✔
587
        self.original_window: str | None = None
1✔
588

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

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

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

621
            # about:blank に移動してレンダラーの状態をリセット
622
            self.driver.get("about:blank")
×
623
            time.sleep(0.5)
×
624
        except Exception:
×
625
            logging.warning("ブラウザの回復に失敗しました")
×
626

627
    def __exit__(
1✔
628
        self,
629
        exception_type: type[BaseException] | None,
630
        exception_value: BaseException | None,
631
        traceback: types.TracebackType | None,
632
    ) -> None:
633
        """タブを閉じて元のウィンドウに戻る"""
634
        self._cleanup()
1✔
635

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

640

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

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

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

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

657
    Examples:
658
        基本的な使用方法::
659

660
            with my_lib.selenium_util.error_handler(driver, message="ログイン処理に失敗") as handler:
661
                driver.get(login_url)
662
                driver.find_element(...).click()
663

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

666
            def notify(exc, screenshot):
667
                slack.error("エラー発生", str(exc), screenshot)
668

669
            with my_lib.selenium_util.error_handler(
670
                driver,
671
                message="クロール処理に失敗",
672
                on_error=notify,
673
            ):
674
                crawl_page(driver)
675

676
        例外を抑制して続行::
677

678
            with my_lib.selenium_util.error_handler(driver, reraise=False) as handler:
679
                risky_operation()
680

681
            if handler.exception:
682
                logging.warning("処理をスキップしました")
683

684
    """
685

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

703
    def __enter__(self) -> Self:
1✔
704
        """コンテキストマネージャの開始"""
705
        return self
1✔
706

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

717
        # 例外を記録
718
        if isinstance(exception_value, Exception):
1✔
719
            self.exception = exception_value
1✔
720
        else:
721
            # BaseException(KeyboardInterrupt など)は処理せず再送出
722
            return False
×
723

724
        # ログ出力
725
        logging.exception(self.message)
1✔
726

727
        # スクリーンショット取得
728
        if self.capture_screenshot:
1✔
729
            try:
1✔
730
                screenshot_bytes = self.driver.get_screenshot_as_png()
1✔
731
                self.screenshot = PIL.Image.open(io.BytesIO(screenshot_bytes))
1✔
732
            except Exception:
1✔
733
                logging.debug("Failed to capture screenshot for error handling")
1✔
734

735
        # コールバック呼び出し
736
        if self.on_error is not None:
1✔
737
            try:
1✔
738
                self.on_error(self.exception, self.screenshot)
1✔
739
            except Exception:
×
740
                logging.exception("Error in on_error callback")
×
741

742
        # reraise=False なら例外を抑制
743
        return not self.reraise
1✔
744

745

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

759

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

784

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

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

793
    # 1. driver.service.process の子プロセスを検索
794
    try:
×
795
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "process"):  # type: ignore[attr-defined]
×
796
            process = driver.service.process  # type: ignore[attr-defined]
×
797
            if process and hasattr(process, "pid"):
×
798
                chromedriver_pid = process.pid
×
799

800
                # psutilでプロセス階層を取得
801
                parent_process = psutil.Process(chromedriver_pid)
×
802
                children = parent_process.children(recursive=True)
×
803

804
                for child in children:
×
805
                    chrome_pids.add(child.pid)
×
806
                    logging.debug(
×
807
                        "Found Chrome-related process (service child): PID %d, name: %s",
808
                        child.pid,
809
                        child.name(),
810
                    )
811
    except Exception:
×
812
        logging.exception("Failed to get Chrome-related processes from service")
×
813

814
    # 2. 現在の Python プロセスの全子孫から Chrome 関連プロセスを検索
815
    try:
×
816
        current_process = psutil.Process()
×
817
        all_children = current_process.children(recursive=True)
×
818

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

835
    return list(chrome_pids)
×
836

837

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

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

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

863

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

867
    Args:
868
        chrome_pids: 終了対象のプロセスIDリスト
869
        timeout: SIGTERM後にプロセス終了を待機する最大時間(秒)
870

871
    """
872
    if not chrome_pids:
×
873
        return
×
874

875
    # 優雅な終了(SIGTERM)
876
    _send_signal_to_processes(chrome_pids, signal.SIGTERM, "SIGTERM")
×
877

878
    # プロセスの終了を待機(ポーリング)
879
    remaining_pids = list(chrome_pids)
×
880
    poll_interval = 0.2
×
881
    elapsed = 0.0
×
882

883
    while remaining_pids and elapsed < timeout:
×
884
        time.sleep(poll_interval)
×
885
        elapsed += poll_interval
×
886

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

898
        remaining_pids = still_alive
×
899

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

909

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

927

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

933

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

951

952
def _wait_for_processes_with_check(
1✔
953
    chrome_pids: list[int],
954
    timeout: float,
955
    poll_interval: float = 0.2,
956
    log_interval: float = 1.0,
957
) -> list[int]:
958
    """プロセスの終了を待機しつつ、残存プロセスをチェック
959

960
    Args:
961
        chrome_pids: 監視対象のプロセスIDリスト
962
        timeout: 最大待機時間(秒)
963
        poll_interval: チェック間隔(秒)
964
        log_interval: ログ出力間隔(秒)
965

966
    Returns:
967
        タイムアウト後も残存しているプロセスIDのリスト
968

969
    """
970
    elapsed = 0.0
×
971
    last_log_time = 0.0
×
972
    remaining_pids = list(chrome_pids)
×
973

974
    while remaining_pids and elapsed < timeout:
×
975
        time.sleep(poll_interval)
×
976
        elapsed += poll_interval
×
977
        remaining_pids = _get_remaining_chrome_pids(remaining_pids)
×
978

979
        if remaining_pids and (elapsed - last_log_time) >= log_interval:
×
980
            logging.info(
×
981
                "Found %d remaining Chrome processes after %.0fs",
982
                len(remaining_pids),
983
                elapsed,
984
            )
985
            last_log_time = elapsed
×
986

987
    return remaining_pids
×
988

989

990
def quit_driver_gracefully(
1✔
991
    driver: WebDriver | None,
992
    wait_sec: float = 5.0,
993
    sigterm_wait_sec: float = 5.0,
994
    sigkill_wait_sec: float = 5.0,
995
) -> None:
996
    """Chrome WebDriverを確実に終了する
997

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

1006
    Args:
1007
        driver: 終了する WebDriver インスタンス
1008
        wait_sec: quit 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1009
        sigterm_wait_sec: SIGTERM 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1010
        sigkill_wait_sec: SIGKILL 後にプロセス回収を待機する秒数(デフォルト: 5秒)
1011

1012
    """
1013
    if driver is None:
1✔
1014
        return
1✔
1015

1016
    # quit前にChrome関連プロセスを記録
1017
    chrome_pids_before = _get_chrome_related_processes(driver)
1✔
1018

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

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

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

1043
    if not remaining_pids:
1✔
1044
        logging.debug("All Chrome processes exited normally")
1✔
1045
        return
1✔
1046

1047
    # Step 2: 残存プロセスに SIGTERM を送信
1048
    logging.info(
×
1049
        "Found %d remaining Chrome processes after %.0fs, sending SIGTERM",
1050
        len(remaining_pids),
1051
        wait_sec,
1052
    )
1053
    _send_signal_to_processes(remaining_pids, signal.SIGTERM, "SIGTERM")
×
1054

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

1058
    if not remaining_pids:
×
1059
        logging.info("All Chrome processes exited after SIGTERM")
×
1060
        _reap_chrome_processes(chrome_pids_before)
×
1061
        return
×
1062

1063
    # Step 4: 残存プロセスに SIGKILL を送信
1064
    logging.warning(
×
1065
        "Chrome processes still alive after SIGTERM + %.1fs, sending SIGKILL to %d processes",
1066
        sigterm_wait_sec,
1067
        len(remaining_pids),
1068
    )
1069
    _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1070

1071
    # Step 5: SIGKILL 後に sigkill_wait_sec 秒待機してプロセス回収
1072
    time.sleep(sigkill_wait_sec)
×
1073
    _reap_chrome_processes(chrome_pids_before)
×
1074

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

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

1087

1088
if __name__ == "__main__":
1089
    import pathlib
1090

1091
    import docopt
1092
    import selenium.webdriver.support.wait
1093

1094
    import my_lib.config
1095
    import my_lib.logger
1096

1097
    assert __doc__ is not None  # noqa: S101
1098
    args = docopt.docopt(__doc__)
1099

1100
    config_file = args["-c"]
1101
    debug_mode = args["-D"]
1102

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

1105
    config = my_lib.config.load(config_file)
1106

1107
    driver = create_driver("test", pathlib.Path(config["data"]["selenium"]))
1108
    wait = selenium.webdriver.support.wait.WebDriverWait(driver, 5)
1109

1110
    driver.get("https://www.google.com/")
1111
    wait.until(
1112
        selenium.webdriver.support.expected_conditions.presence_of_element_located(
1113
            (selenium.webdriver.common.by.By.XPATH, '//input[contains(@value, "Google")]')
1114
        )
1115
    )
1116

1117
    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