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

kimata / my-py-lib / 21325946036

25 Jan 2026 03:06AM UTC coverage: 63.351% (-0.2%) from 63.538%
21325946036

push

github

kimata
fix(test): pytest_util.get_path() の新仕様に合わせてテストを修正

fe318dc で変更された get_path() の動作に合わせてアサーションを更新:
- PYTEST_XDIST_WORKER 未設定時は元のパスをそのまま返す
- 設定時は .{worker_id} サフィックスを付加する

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

3535 of 5580 relevant lines covered (63.35%)

0.63 hits per line

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

36.2
/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

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

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

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

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

52
WAIT_RETRY_COUNT: int = 1
1✔
53

54

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

58

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

75

76
def _create_chrome_options(
1✔
77
    profile_name: str,
78
    chrome_data_path: pathlib.Path,
79
    log_path: pathlib.Path,
80
    is_headless: bool,
81
) -> selenium.webdriver.chrome.options.Options:
82
    """Chrome オプションを作成する
83

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

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

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
    return options
×
126

127

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

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

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

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

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

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

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

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

165
    if use_undetected:
×
166
        import undetected_chromedriver
×
167

168
        chrome_version = _get_chrome_version()
×
169

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

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

188
    driver.set_page_load_timeout(30)
×
189

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

193
    # ボット検出回避のための設定を適用
194
    set_stealth_mode(driver)
×
195

196
    return driver
×
197

198

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

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

219
    Raises:
220
        ValueError: use_undetected=False かつ use_subprocess=True の場合
221

222
    """
223
    if not use_undetected and use_subprocess:
×
224
        raise ValueError("use_subprocess=True は use_undetected=True の場合のみ有効です")
×
225

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

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

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

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

252
    if clean_profile:
×
253
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
254

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

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

264
        # プロファイルのロックファイルを削除
265
        my_lib.chrome_util._cleanup_profile_lock(profile_path)
×
266

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

273
        return _create_driver_impl(profile_name, data_path, is_headless, use_subprocess, use_undetected)
×
274

275

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

279

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

293
    if len(driver.find_elements(selenium.webdriver.common.by.By.XPATH, xpath)) != 0:
×
294
        return driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath).text.strip()
×
295
    else:
296
        return safe_text
×
297

298

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

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

322

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

338
    if xpath_exists(driver, xpath):
×
339
        elem = driver.find_element(selenium.webdriver.common.by.By.XPATH, xpath)
×
340
        if move:
×
341
            action = selenium.webdriver.common.action_chains.ActionChains(driver)
×
342
            action.move_to_element(elem)
×
343
            action.perform()
×
344

345
        elem.click()
×
346
        return True
×
347
    else:
348
        if is_warn:
×
349
            logging.warning("Element is not found: %s", xpath)
×
350
        return False
×
351

352

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

358

359
def random_sleep(sec: float) -> None:
1✔
360
    RATIO = 0.8
1✔
361

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

364

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

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

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

386
    Returns:
387
        成功時は関数の戻り値
388

389
    Raises:
390
        最後の例外を再スロー
391

392
    """
393
    last_exception: Exception | None = None
1✔
394

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

407
    if last_exception:
1✔
408
        raise last_exception
1✔
409
    raise RuntimeError("Unexpected state in with_retry")
×
410

411

412
def with_session_retry(
1✔
413
    func: Callable[[], T],
414
    driver_name: str,
415
    data_dir: pathlib.Path,
416
    *,
417
    max_retries: int = 1,
418
    clear_profile_on_error: bool = True,
419
    on_retry: Callable[[int, int], None] | None = None,
420
    before_retry: Callable[[], None] | None = None,
421
) -> T:
422
    """InvalidSessionIdException 発生時にプロファイル削除してリトライ
423

424
    ブラウザのセッションが無効になった場合(クラッシュ等)、
425
    プロファイルを削除して再起動することで復旧を試みる。
426

427
    Args:
428
        func: 実行する関数
429
        driver_name: Chrome プロファイル名
430
        data_dir: Selenium データディレクトリ
431
        max_retries: 最大リトライ回数 (デフォルト: 1)
432
        clear_profile_on_error: エラー時にプロファイルを削除するか
433
        on_retry: リトライ時のコールバック (attempt, max_retries) - ステータス更新用
434
        before_retry: リトライ前のコールバック - quit_selenium() 呼び出し用
435

436
    Returns:
437
        成功時は関数の戻り値
438

439
    Raises:
440
        InvalidSessionIdException: リトライ上限に達した場合
441

442
    """
443

444
    def retry_handler(attempt: int, exception: Exception) -> bool | None:
1✔
445
        if before_retry:
1✔
446
            before_retry()
1✔
447

448
        if attempt <= max_retries and clear_profile_on_error:
1✔
449
            logging.warning(
1✔
450
                "セッションエラーが発生しました。プロファイルを削除してリトライします(%d/%d)",
451
                attempt,
452
                max_retries,
453
            )
454
            if on_retry:
1✔
455
                on_retry(attempt, max_retries)
1✔
456
            my_lib.chrome_util.delete_profile(driver_name, data_dir)
1✔
457
            return True
1✔
458
        return False
1✔
459

460
    return with_retry(
1✔
461
        func,
462
        max_retries=max_retries + 1,
463
        delay=0,
464
        exceptions=(selenium.common.exceptions.InvalidSessionIdException,),
465
        on_retry=retry_handler,
466
    )
467

468

469
def wait_patiently(
1✔
470
    driver: WebDriver,
471
    wait: WebDriverWait[WebDriver],
472
    target: Any,
473
) -> None:
474
    error: selenium.common.exceptions.TimeoutException | None = None
×
475
    for i in range(WAIT_RETRY_COUNT + 1):
×
476
        try:
×
477
            wait.until(target)
×
478
            return
×
479
        except selenium.common.exceptions.TimeoutException as e:
×
480
            logging.warning(
×
481
                "タイムアウトが発生しました。(%s in %s line %d)",
482
                inspect.stack()[1].function,
483
                inspect.stack()[1].filename,
484
                inspect.stack()[1].lineno,
485
            )
486
            error = e
×
487

488
            logging.info(i)
×
489
            if i != WAIT_RETRY_COUNT:
×
490
                logging.info("refresh")
×
491
                driver.refresh()
×
492

493
    if error is not None:
×
494
        raise error
×
495

496

497
def dump_page(
1✔
498
    driver: WebDriver,
499
    index: int,
500
    dump_path: pathlib.Path,
501
    stack_index: int = 1,
502
) -> None:
503
    name = inspect.stack()[stack_index].function.replace("<", "").replace(">", "")
×
504

505
    dump_path.mkdir(parents=True, exist_ok=True)
×
506

507
    png_path = dump_path / f"{name}_{index:02d}.png"
×
508
    htm_path = dump_path / f"{name}_{index:02d}.htm"
×
509

510
    driver.save_screenshot(str(png_path))
×
511

512
    with htm_path.open("w", encoding="utf-8") as f:
×
513
        f.write(driver.page_source)
×
514

515
    logging.info(
×
516
        "page dump: %02d from %s in %s line %d",
517
        index,
518
        inspect.stack()[stack_index].function,
519
        inspect.stack()[stack_index].filename,
520
        inspect.stack()[stack_index].lineno,
521
    )
522

523

524
def clear_cache(driver: WebDriver) -> None:
1✔
525
    driver.execute_cdp_cmd("Network.clearBrowserCache", {})
×
526

527

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

531
    Chrome の起動オプションだけでは言語設定が変わってしまうことがあるため、
532
    CDP を使って Accept-Language ヘッダーとロケールを強制的に日本語に設定する。
533
    """
534
    try:
×
535
        # NOTE: Network.setExtraHTTPHeaders は Network.enable を先に呼ばないと機能しない
536
        driver.execute_cdp_cmd("Network.enable", {})
×
537
        driver.execute_cdp_cmd(
×
538
            "Network.setExtraHTTPHeaders",
539
            {"headers": {"Accept-Language": "ja-JP,ja;q=0.9"}},
540
        )
541
        driver.execute_cdp_cmd(
×
542
            "Emulation.setLocaleOverride",
543
            {"locale": "ja-JP"},
544
        )
545
        logging.debug("Japanese locale set via CDP")
×
546
    except Exception:
×
547
        logging.warning("Failed to set Japanese locale via CDP")
×
548

549

550
def _get_stealth_user_agent(driver: WebDriver) -> str:
1✔
551
    """ブラウザの User-Agent を取得し、ボット検出回避用に修正.
552

553
    - OS 部分を Windows に変更
554
    - HeadlessChrome を Chrome に変更
555

556
    Args:
557
        driver: WebDriver インスタンス
558

559
    Returns:
560
        修正された User-Agent 文字列
561

562
    """
563
    original_ua = driver.execute_script("return navigator.userAgent")
×
564
    logging.debug("Original User-Agent: %s", original_ua)
×
565

566
    # OS 部分を Windows に変更
567
    pattern = r"\([^)]*(?:Linux|Macintosh|X11)[^)]*\)"
×
568
    replacement = "(Windows NT 10.0; Win64; x64)"
×
569
    modified_ua = re.sub(pattern, replacement, original_ua)
×
570

571
    # HeadlessChrome を Chrome に変更
572
    modified_ua = modified_ua.replace("HeadlessChrome", "Chrome")
×
573

574
    logging.debug("Modified User-Agent: %s", modified_ua)
×
575
    return modified_ua
×
576

577

578
def set_stealth_mode(driver: WebDriver) -> None:
1✔
579
    """ボット検出回避のための CDP 設定を適用.
580

581
    ヨドバシ等のボット検出は User-Agent をチェックしているため、
582
    OS を Windows に偽装し、HeadlessChrome を Chrome に変更することで回避できる。
583

584
    Args:
585
        driver: WebDriver インスタンス
586

587
    """
588
    try:
×
589
        modified_ua = _get_stealth_user_agent(driver)
×
590
        driver.execute_cdp_cmd(
×
591
            "Network.setUserAgentOverride",
592
            {
593
                "userAgent": modified_ua,
594
                "acceptLanguage": "ja-JP,ja;q=0.9,en-US;q=0.8,en;q=0.7",
595
                "platform": "Win32",
596
            },
597
        )
598
        logging.debug("Stealth mode enabled (User-Agent override applied)")
×
599
    except Exception:
×
600
        logging.warning("Failed to enable stealth mode")
×
601

602

603
def clean_dump(dump_path: pathlib.Path, keep_days: int = 1) -> None:
1✔
604
    if not dump_path.exists():
1✔
605
        return
1✔
606

607
    time_threshold = datetime.timedelta(keep_days)
1✔
608

609
    for item in dump_path.iterdir():
1✔
610
        if not item.is_file():
1✔
611
            continue
1✔
612
        try:
1✔
613
            time_diff = datetime.datetime.now(datetime.UTC) - datetime.datetime.fromtimestamp(
1✔
614
                item.stat().st_mtime, datetime.UTC
615
            )
616
        except FileNotFoundError:
×
617
            # ファイルが別プロセスにより削除された場合(SQLiteの一時ファイルなど)
618
            continue
×
619
        if time_diff > time_threshold:
1✔
620
            logging.warning("remove %s [%s day(s) old].", item.absolute(), f"{time_diff.days:,}")
1✔
621

622
            item.unlink(missing_ok=True)
1✔
623

624

625
def get_memory_info(driver: WebDriver) -> dict[str, Any]:
1✔
626
    """ブラウザのメモリ使用量を取得(単位: KB)"""
627
    total_bytes = subprocess.Popen(  # noqa: S602
×
628
        "smem -t -c pss -P chrome | tail -n 1",  # noqa: S607
629
        shell=True,
630
        stdout=subprocess.PIPE,
631
    ).communicate()[0]
632
    total = int(str(total_bytes, "utf-8").strip())  # smem の出力は KB 単位
×
633

634
    try:
×
635
        memory_info = driver.execute_cdp_cmd("Memory.getAllTimeSamplingProfile", {})
×
636
        heap_usage = driver.execute_cdp_cmd("Runtime.getHeapUsage", {})
×
637

638
        heap_used = heap_usage.get("usedSize", 0) // 1024  # bytes → KB
×
639
        heap_total = heap_usage.get("totalSize", 0) // 1024  # bytes → KB
×
640
    except Exception as e:
×
641
        logging.debug("Failed to get memory usage: %s", e)
×
642

643
        memory_info = None
×
644
        heap_used = 0
×
645
        heap_total = 0
×
646

647
    return {
×
648
        "total": total,
649
        "heap_used": heap_used,
650
        "heap_total": heap_total,
651
        "memory_info": memory_info,
652
    }
653

654

655
def log_memory_usage(driver: WebDriver) -> None:
1✔
656
    mem_info = get_memory_info(driver)
×
657
    logging.info(
×
658
        "Chrome memory: %s MB (JS heap: %s MB)",
659
        f"""{mem_info["total"] // 1024:,}""",
660
        f"""{mem_info["heap_used"] // 1024:,}""",
661
    )
662

663

664
def _warmup(
1✔
665
    driver: WebDriver,
666
    keyword: str,
667
    url_pattern: str,
668
    sleep_sec: int = 3,
669
) -> None:
670
    # NOTE: ダミーアクセスを行って BOT ではないと思わせる。(効果なさそう...)
671
    driver.get("https://www.yahoo.co.jp/")
×
672
    time.sleep(sleep_sec)
×
673

674
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(keyword)
×
675
    driver.find_element(selenium.webdriver.common.by.By.XPATH, '//input[@name="p"]').send_keys(
×
676
        selenium.webdriver.common.keys.Keys.ENTER
677
    )
678

679
    time.sleep(sleep_sec)
×
680

681
    driver.find_element(
×
682
        selenium.webdriver.common.by.By.XPATH, f'//a[contains(@href, "{url_pattern}")]'
683
    ).click()
684

685
    time.sleep(sleep_sec)
×
686

687

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

691
    def __init__(self, driver: WebDriver, url: str) -> None:
1✔
692
        """初期化
693

694
        Args:
695
            driver: WebDriver インスタンス
696
            url: 開く URL
697

698
        """
699
        self.driver = driver
1✔
700
        self.url = url
1✔
701
        self.original_window: str | None = None
1✔
702

703
    def __enter__(self) -> None:
1✔
704
        """新しいタブを開いて URL にアクセス"""
705
        self.original_window = self.driver.current_window_handle
1✔
706
        self.driver.execute_script("window.open('');")
1✔
707
        self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
708
        try:
1✔
709
            self.driver.get(self.url)
1✔
710
        except Exception:
×
711
            # NOTE: URL読み込みに失敗した場合もクリーンアップしてから例外を再送出
712
            self._cleanup()
×
713
            raise
×
714

715
    def _cleanup(self) -> None:
1✔
716
        """タブを閉じて元のウィンドウに戻る"""
717
        try:
1✔
718
            # 余分なタブを閉じる
719
            while len(self.driver.window_handles) > 1:
1✔
720
                self.driver.switch_to.window(self.driver.window_handles[-1])
1✔
721
                self.driver.close()
1✔
722
            if self.original_window is not None:
1✔
723
                self.driver.switch_to.window(self.original_window)
1✔
724
            time.sleep(0.1)
1✔
725
        except Exception:
1✔
726
            # NOTE: Chromeがクラッシュした場合は無視(既に終了しているため操作不可)
727
            logging.exception("タブのクリーンアップに失敗しました(Chromeがクラッシュした可能性があります)")
1✔
728

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

735
            # about:blank に移動してレンダラーの状態をリセット
736
            self.driver.get("about:blank")
×
737
            time.sleep(0.5)
×
738
        except Exception:
×
739
            logging.warning("ブラウザの回復に失敗しました")
×
740

741
    def __exit__(
1✔
742
        self,
743
        exception_type: type[BaseException] | None,
744
        exception_value: BaseException | None,
745
        traceback: types.TracebackType | None,
746
    ) -> None:
747
        """タブを閉じて元のウィンドウに戻る"""
748
        self._cleanup()
1✔
749

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

754

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

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

760
    Args:
761
        driver: WebDriver インスタンス
762
        message: ログに出力するエラーメッセージ
763
        on_error: エラー時に呼ばれるコールバック関数
764
            (exception, screenshot: PIL.Image.Image | None, page_source: str | None) -> None
765
        capture_screenshot: スクリーンショットを自動取得するか(デフォルト: True)
766
        reraise: 例外を再送出するか(デフォルト: True)
767

768
    Attributes:
769
        exception: 発生した例外(エラーがなければ None)
770
        screenshot: 取得したスクリーンショット(PIL.Image.Image、取得失敗時は None)
771
        page_source: 取得したページソース(取得失敗時は None)
772

773
    Examples:
774
        基本的な使用方法::
775

776
            with my_lib.selenium_util.error_handler(driver, message="ログイン処理に失敗") as handler:
777
                driver.get(login_url)
778
                driver.find_element(...).click()
779

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

782
            def notify(exc, screenshot, page_source):
783
                slack.notify_error_with_page(config, "エラー発生", exc, screenshot, page_source)
784

785
            with my_lib.selenium_util.error_handler(
786
                driver,
787
                message="クロール処理に失敗",
788
                on_error=notify,
789
            ):
790
                crawl_page(driver)
791

792
        例外を抑制して続行::
793

794
            with my_lib.selenium_util.error_handler(driver, reraise=False) as handler:
795
                risky_operation()
796

797
            if handler.exception:
798
                logging.warning("処理をスキップしました")
799

800
    """
801

802
    def __init__(
1✔
803
        self,
804
        driver: WebDriver,
805
        message: str = "Selenium operation failed",
806
        on_error: Callable[[Exception, PIL.Image.Image | None, str | None], None] | None = None,
807
        capture_screenshot: bool = True,
808
        reraise: bool = True,
809
    ) -> None:
810
        """初期化"""
811
        self.driver = driver
1✔
812
        self.message = message
1✔
813
        self.on_error = on_error
1✔
814
        self.capture_screenshot = capture_screenshot
1✔
815
        self.reraise = reraise
1✔
816
        self.exception: Exception | None = None
1✔
817
        self.screenshot: PIL.Image.Image | None = None
1✔
818
        self.page_source: str | None = None
1✔
819

820
    def __enter__(self) -> Self:
1✔
821
        """コンテキストマネージャの開始"""
822
        return self
1✔
823

824
    def __exit__(
1✔
825
        self,
826
        exception_type: type[BaseException] | None,
827
        exception_value: BaseException | None,
828
        traceback: types.TracebackType | None,
829
    ) -> bool:
830
        """コンテキストマネージャの終了、エラー処理を実行"""
831
        if exception_value is None:
1✔
832
            return False
1✔
833

834
        # 例外を記録
835
        if isinstance(exception_value, Exception):
1✔
836
            self.exception = exception_value
1✔
837
        else:
838
            # BaseException(KeyboardInterrupt など)は処理せず再送出
839
            return False
×
840

841
        # ログ出力
842
        logging.exception(self.message)
1✔
843

844
        # スクリーンショット・ページソース取得
845
        if self.capture_screenshot:
1✔
846
            try:
1✔
847
                self.page_source = self.driver.page_source
1✔
848
            except Exception:
×
849
                logging.debug("Failed to capture page source for error handling")
×
850
            try:
1✔
851
                screenshot_bytes = self.driver.get_screenshot_as_png()
1✔
852
                self.screenshot = PIL.Image.open(io.BytesIO(screenshot_bytes))
1✔
853
            except Exception:
1✔
854
                logging.debug("Failed to capture screenshot for error handling")
1✔
855

856
        # コールバック呼び出し
857
        if self.on_error is not None:
1✔
858
            try:
1✔
859
                self.on_error(self.exception, self.screenshot, self.page_source)
1✔
860
            except Exception:
×
861
                logging.exception("Error in on_error callback")
×
862

863
        # reraise=False なら例外を抑制
864
        return not self.reraise
1✔
865

866

867
def _is_chrome_related_process(process: psutil.Process) -> bool:
1✔
868
    """プロセスがChrome関連かどうかを判定"""
869
    try:
1✔
870
        process_name = process.name().lower()
1✔
871
        # Chrome関連のプロセス名パターン
872
        chrome_patterns = ["chrome", "chromium", "google-chrome", "undetected_chro"]
1✔
873
        # chromedriverは除外
874
        if "chromedriver" in process_name:
1✔
875
            return False
1✔
876
        return any(pattern in process_name for pattern in chrome_patterns)
1✔
877
    except (psutil.NoSuchProcess, psutil.AccessDenied):
1✔
878
        return False
1✔
879

880

881
def _get_chrome_processes_by_pgid(chromedriver_pid: int, existing_pids: set[int]) -> list[int]:
1✔
882
    """プロセスグループIDで追加のChrome関連プロセスを取得"""
883
    additional_pids = []
×
884
    try:
×
885
        pgid = os.getpgid(chromedriver_pid)
×
886
        for proc in psutil.process_iter(["pid", "name", "ppid"]):
×
887
            if proc.info["pid"] in existing_pids:
×
888
                continue
×
889
            try:
×
890
                if os.getpgid(proc.info["pid"]) == pgid:
×
891
                    proc_obj = psutil.Process(proc.info["pid"])
×
892
                    if _is_chrome_related_process(proc_obj):
×
893
                        additional_pids.append(proc.info["pid"])
×
894
                        logging.debug(
×
895
                            "Found Chrome-related process by pgid: PID %d, name: %s",
896
                            proc.info["pid"],
897
                            proc.info["name"],
898
                        )
899
            except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
×
900
                pass
×
901
    except (OSError, psutil.NoSuchProcess):
×
902
        logging.debug("Failed to get process group ID for chromedriver")
×
903
    return additional_pids
×
904

905

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

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

914
    # 1. driver.service.process の子プロセスを検索
915
    # NOTE: Chrome/Firefox WebDriver には service 属性があるが、型スタブでは定義されていない
916
    try:
×
917
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "process"):  # type: ignore[union-attr]
×
918
            process = driver.service.process  # type: ignore[union-attr]
×
919
            if process and hasattr(process, "pid"):
×
920
                chromedriver_pid = process.pid
×
921

922
                # psutilでプロセス階層を取得
923
                parent_process = psutil.Process(chromedriver_pid)
×
924
                children = parent_process.children(recursive=True)
×
925

926
                for child in children:
×
927
                    chrome_pids.add(child.pid)
×
928
                    logging.debug(
×
929
                        "Found Chrome-related process (service child): PID %d, name: %s",
930
                        child.pid,
931
                        child.name(),
932
                    )
933
    except Exception:
×
934
        logging.exception("Failed to get Chrome-related processes from service")
×
935

936
    # 2. 現在の Python プロセスの全子孫から Chrome 関連プロセスを検索
937
    try:
×
938
        current_process = psutil.Process()
×
939
        all_children = current_process.children(recursive=True)
×
940

941
        for child in all_children:
×
942
            if child.pid in chrome_pids:
×
943
                continue
×
944
            try:
×
945
                if _is_chrome_related_process(child):
×
946
                    chrome_pids.add(child.pid)
×
947
                    logging.debug(
×
948
                        "Found Chrome-related process (python child): PID %d, name: %s",
949
                        child.pid,
950
                        child.name(),
951
                    )
952
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
953
                pass
×
954
    except Exception:
×
955
        logging.exception("Failed to get Chrome-related processes from python children")
×
956

957
    return list(chrome_pids)
×
958

959

960
def _send_signal_to_processes(pids: list[int], sig: signal.Signals, signal_name: str) -> None:
1✔
961
    """プロセスリストに指定されたシグナルを送信"""
962
    errors = []
×
963
    for pid in pids:
×
964
        try:
×
965
            # プロセス名を取得
966
            try:
×
967
                process = psutil.Process(pid)
×
968
                process_name = process.name()
×
969
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
970
                process_name = "unknown"
×
971

972
            if sig == signal.SIGKILL:
×
973
                # プロセスがまだ存在するかチェック
974
                os.kill(pid, 0)  # シグナル0は存在確認
×
975
            os.kill(pid, sig)
×
976
            logging.info("Sent %s to process: PID %d (%s)", signal_name, pid, process_name)
×
977
        except (ProcessLookupError, OSError) as e:
×
978
            # プロセスが既に終了している場合は無視
979
            errors.append((pid, e))
×
980

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

985

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

989
    Args:
990
        chrome_pids: 終了対象のプロセスIDリスト
991
        timeout: SIGTERM後にプロセス終了を待機する最大時間(秒)
992

993
    """
994
    if not chrome_pids:
×
995
        return
×
996

997
    # 優雅な終了(SIGTERM)
998
    _send_signal_to_processes(chrome_pids, signal.SIGTERM, "SIGTERM")
×
999

1000
    # プロセスの終了を待機(ポーリング)
1001
    remaining_pids = list(chrome_pids)
×
1002
    poll_interval = 0.2
×
1003
    elapsed = 0.0
×
1004

1005
    while remaining_pids and elapsed < timeout:
×
1006
        time.sleep(poll_interval)
×
1007
        elapsed += poll_interval
×
1008

1009
        # まだ生存しているプロセスをチェック
1010
        still_alive = []
×
1011
        for pid in remaining_pids:
×
1012
            try:
×
1013
                if psutil.pid_exists(pid):
×
1014
                    process = psutil.Process(pid)
×
1015
                    if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
×
1016
                        still_alive.append(pid)
×
1017
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1018
                pass
×
1019

1020
        remaining_pids = still_alive
×
1021

1022
    # タイムアウト後もまだ残っているプロセスにのみ SIGKILL を送信
1023
    if remaining_pids:
×
1024
        logging.warning(
×
1025
            "Chrome processes still alive after %.1fs, sending SIGKILL to %d processes",
1026
            elapsed,
1027
            len(remaining_pids),
1028
        )
1029
        _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1030

1031

1032
def _reap_single_process(pid: int) -> None:
1✔
1033
    """単一プロセスをwaitpidで回収"""
1034
    try:
×
1035
        # ノンブロッキングでwaitpid
1036
        result_pid, status = os.waitpid(pid, os.WNOHANG)
×
1037
        if result_pid == pid:
×
1038
            # プロセス名を取得
1039
            try:
×
1040
                process = psutil.Process(pid)
×
1041
                process_name = process.name()
×
1042
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1043
                process_name = "unknown"
×
1044
            logging.debug("Reaped Chrome process: PID %d (%s)", pid, process_name)
×
1045
    except (ChildProcessError, OSError):
×
1046
        # 子プロセスでない場合や既に回収済みの場合は無視
1047
        pass
×
1048

1049

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

1055

1056
def _get_remaining_chrome_pids(chrome_pids: list[int]) -> list[int]:
1✔
1057
    """指定されたPIDリストから、まだ生存しているChrome関連プロセスを取得"""
1058
    remaining = []
×
1059
    for pid in chrome_pids:
×
1060
        try:
×
1061
            if psutil.pid_exists(pid):
×
1062
                process = psutil.Process(pid)
×
1063
                if (
×
1064
                    process.is_running()
1065
                    and process.status() != psutil.STATUS_ZOMBIE
1066
                    and _is_chrome_related_process(process)
1067
                ):
1068
                    remaining.append(pid)
×
1069
        except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1070
            pass
×
1071
    return remaining
×
1072

1073

1074
def _wait_for_processes_with_check(
1✔
1075
    chrome_pids: list[int],
1076
    timeout: float,
1077
    poll_interval: float = 0.2,
1078
    log_interval: float = 1.0,
1079
) -> list[int]:
1080
    """プロセスの終了を待機しつつ、残存プロセスをチェック
1081

1082
    Args:
1083
        chrome_pids: 監視対象のプロセスIDリスト
1084
        timeout: 最大待機時間(秒)
1085
        poll_interval: チェック間隔(秒)
1086
        log_interval: ログ出力間隔(秒)
1087

1088
    Returns:
1089
        タイムアウト後も残存しているプロセスIDのリスト
1090

1091
    """
1092
    elapsed = 0.0
×
1093
    last_log_time = 0.0
×
1094
    remaining_pids = list(chrome_pids)
×
1095

1096
    while remaining_pids and elapsed < timeout:
×
1097
        time.sleep(poll_interval)
×
1098
        elapsed += poll_interval
×
1099
        remaining_pids = _get_remaining_chrome_pids(remaining_pids)
×
1100

1101
        if remaining_pids and (elapsed - last_log_time) >= log_interval:
×
1102
            logging.info(
×
1103
                "Found %d remaining Chrome processes after %.0fs",
1104
                len(remaining_pids),
1105
                elapsed,
1106
            )
1107
            last_log_time = elapsed
×
1108

1109
    return remaining_pids
×
1110

1111

1112
def quit_driver_gracefully(
1✔
1113
    driver: WebDriver | None,
1114
    wait_sec: float = 5.0,
1115
    sigterm_wait_sec: float = 5.0,
1116
    sigkill_wait_sec: float = 5.0,
1117
) -> None:
1118
    """Chrome WebDriverを確実に終了する
1119

1120
    終了フロー:
1121
    1. driver.quit() を呼び出し
1122
    2. wait_sec 秒待機しつつプロセス終了をチェック
1123
    3. 残存プロセスがあれば SIGTERM を送信
1124
    4. sigterm_wait_sec 秒待機しつつプロセス終了をチェック
1125
    5. 残存プロセスがあれば SIGKILL を送信
1126
    6. sigkill_wait_sec 秒待機
1127

1128
    Args:
1129
        driver: 終了する WebDriver インスタンス
1130
        wait_sec: quit 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1131
        sigterm_wait_sec: SIGTERM 後にプロセス終了を待機する秒数(デフォルト: 5秒)
1132
        sigkill_wait_sec: SIGKILL 後にプロセス回収を待機する秒数(デフォルト: 5秒)
1133

1134
    """
1135
    if driver is None:
1✔
1136
        return
1✔
1137

1138
    # quit前にChrome関連プロセスを記録
1139
    chrome_pids_before = _get_chrome_related_processes(driver)
1✔
1140

1141
    try:
1✔
1142
        # WebDriverの正常終了を試行(これがタブのクローズも含む)
1143
        driver.quit()
1✔
1144
        logging.info("WebDriver quit successfully")
1✔
1145
    except Exception:
1✔
1146
        logging.warning("Failed to quit driver normally", exc_info=True)
1✔
1147
    finally:
1148
        # undetected_chromedriver の __del__ がシャットダウン時に再度呼ばれるのを防ぐ
1149
        if hasattr(driver, "_has_quit"):
1✔
1150
            driver._has_quit = True  # type: ignore[attr-defined]
1✔
1151

1152
    # ChromeDriverサービスの停止を試行
1153
    try:
1✔
1154
        if hasattr(driver, "service") and driver.service and hasattr(driver.service, "stop"):  # type: ignore[union-attr]
1✔
1155
            driver.service.stop()  # type: ignore[union-attr]
×
1156
    except (ConnectionResetError, OSError):
×
1157
        # Chrome が既に終了している場合は無視
1158
        logging.debug("Chrome service already stopped")
×
1159
    except Exception:
×
1160
        logging.warning("Failed to stop Chrome service", exc_info=True)
×
1161

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

1165
    if not remaining_pids:
1✔
1166
        logging.debug("All Chrome processes exited normally")
1✔
1167
        return
1✔
1168

1169
    # Step 2: 残存プロセスに SIGTERM を送信
1170
    logging.info(
×
1171
        "Found %d remaining Chrome processes after %.0fs, sending SIGTERM",
1172
        len(remaining_pids),
1173
        wait_sec,
1174
    )
1175
    _send_signal_to_processes(remaining_pids, signal.SIGTERM, "SIGTERM")
×
1176

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

1180
    if not remaining_pids:
×
1181
        logging.info("All Chrome processes exited after SIGTERM")
×
1182
        _reap_chrome_processes(chrome_pids_before)
×
1183
        return
×
1184

1185
    # Step 4: 残存プロセスに SIGKILL を送信
1186
    logging.warning(
×
1187
        "Chrome processes still alive after SIGTERM + %.1fs, sending SIGKILL to %d processes",
1188
        sigterm_wait_sec,
1189
        len(remaining_pids),
1190
    )
1191
    _send_signal_to_processes(remaining_pids, signal.SIGKILL, "SIGKILL")
×
1192

1193
    # Step 5: SIGKILL 後に sigkill_wait_sec 秒待機してプロセス回収
1194
    time.sleep(sigkill_wait_sec)
×
1195
    _reap_chrome_processes(chrome_pids_before)
×
1196

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

1200
    # 回収できなかったプロセスについて警告
1201
    if still_remaining:
×
1202
        for pid in still_remaining:
×
1203
            try:
×
1204
                process = psutil.Process(pid)
×
1205
                logging.warning("Failed to collect Chrome-related process: PID %d (%s)", pid, process.name())
×
1206
            except (psutil.NoSuchProcess, psutil.AccessDenied):
×
1207
                pass
×
1208

1209

1210
if __name__ == "__main__":
1211
    import pathlib
1212

1213
    import docopt
1214
    import selenium.webdriver.support.wait
1215

1216
    import my_lib.config
1217
    import my_lib.logger
1218

1219
    assert __doc__ is not None  # noqa: S101
1220
    args = docopt.docopt(__doc__)
1221

1222
    config_file = args["-c"]
1223
    debug_mode = args["-D"]
1224

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

1227
    config = my_lib.config.load(config_file)
1228

1229
    driver = create_driver("test", pathlib.Path(config["data"]["selenium"]))
1230
    wait = selenium.webdriver.support.wait.WebDriverWait(driver, 5)
1231

1232
    driver.get("https://www.google.com/")
1233
    wait.until(
1234
        selenium.webdriver.support.expected_conditions.presence_of_element_located(
1235
            (selenium.webdriver.common.by.By.XPATH, '//input[contains(@value, "Google")]')
1236
        )
1237
    )
1238

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

© 2026 Coveralls, Inc