auth.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. """步骤:登录。"""
  2. from __future__ import annotations
  3. from playwright.sync_api import Page, TimeoutError as PlaywrightTimeoutError
  4. from collectors.douyin.common import human_pause
  5. def click_login_if_needed(page: Page) -> None:
  6. login = page.get_by_role("button", name="登录").or_(page.get_by_text("登录", exact=True)).first
  7. try:
  8. if login.is_visible(timeout=3000):
  9. human_pause(0.8, 1.5)
  10. login.click()
  11. print("已点击登录按钮,请在浏览器中完成人工登录。")
  12. else:
  13. print("未看到登录按钮,可能已登录。")
  14. except PlaywrightTimeoutError:
  15. print("未看到登录按钮,可能已登录。")
  16. def wait_until_logged_in(page: Page, timeout_ms: int = 300_000) -> None:
  17. print("等待人工登录完成(最多 5 分钟)...")
  18. page.wait_for_function(
  19. """() => {
  20. const texts = Array.from(document.querySelectorAll('button, a, span, div'))
  21. .map(el => (el.innerText || '').trim())
  22. .filter(Boolean);
  23. return !texts.some(t => t === '登录');
  24. }""",
  25. timeout=timeout_ms,
  26. )
  27. print("检测到登录态已就绪。")