__init__.py 2.2 KB

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