__init__.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. """
  3. from abc import abstractmethod
  4. import api
  5. from playwright.sync_api import Playwright, sync_playwright
  6. class BaseBrowser:
  7. def __init__(self, phone: str, playwright=None):
  8. api.assert_not_none(phone, "手机号不能为空")
  9. self.phone = phone
  10. self.browser = None
  11. self.page = None
  12. self.result = None
  13. self.list_result = []
  14. self.map_result = {}
  15. self.has_more = False
  16. self.playwright = playwright
  17. def __init_browser__(self):
  18. self.sure_playwright()
  19. self.browser = self.playwright.chromium.launch_persistent_context(
  20. proxy=None,
  21. user_data_dir=f'./.data/{self.__get_name__()}/{self.phone}',
  22. headless=False,
  23. slow_mo=1000,
  24. channel="chrome",
  25. ignore_https_errors=True,
  26. user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
  27. args=[
  28. '--disable-blink-features=AutomationControlled',
  29. '--incognito',
  30. '--ignore-certificate-errors-spki-list',
  31. '--disable-web-security', # 禁用 Web 安全性,类似于 ChromeOptions 中的 --ignore-certificate-errors-spki-list
  32. '--no-sandbox', # 禁用沙盒模式
  33. '--disable-dev-shm-usage', # 禁用/dev/shm使用
  34. '--disable-features=site-per-process', # 禁用每个站点的进程,类似于 ChromeOptions 中的 --no-sandbox
  35. '--ignore-certificate-errors', # 忽略证书错误
  36. '--disable-features=AutomationControlled' # 禁用与自动化相关的特性
  37. ])
  38. self.browser.add_init_script(path="./stealth.min.js")
  39. self.page = self.browser.new_page()
  40. def sure_playwright(self):
  41. if self.playwright is None:
  42. self.playwright = sync_playwright().start()
  43. def close(self):
  44. if self.page is not None:
  45. self.page.close()
  46. if self.browser is not None:
  47. self.browser.close()
  48. @abstractmethod
  49. def __get_name__(self):
  50. pass