__init__.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.has_more = False
  15. self.playwright = playwright
  16. def __init_browser__(self):
  17. self.sure_playwright()
  18. self.browser = self.playwright.chromium.launch_persistent_context(
  19. proxy=None,
  20. user_data_dir=f'./.data/{self.__get_name__()}/{self.phone}',
  21. headless=False,
  22. slow_mo=1000,
  23. channel="chrome",
  24. ignore_https_errors=True,
  25. 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',
  26. args=[
  27. '--disable-blink-features=AutomationControlled',
  28. '--incognito',
  29. '--ignore-certificate-errors-spki-list',
  30. '--disable-web-security', # 禁用 Web 安全性,类似于 ChromeOptions 中的 --ignore-certificate-errors-spki-list
  31. '--no-sandbox', # 禁用沙盒模式
  32. '--disable-dev-shm-usage', # 禁用/dev/shm使用
  33. '--disable-features=site-per-process', # 禁用每个站点的进程,类似于 ChromeOptions 中的 --no-sandbox
  34. '--ignore-certificate-errors', # 忽略证书错误
  35. '--disable-features=AutomationControlled' # 禁用与自动化相关的特性
  36. ])
  37. self.browser.add_init_script(path="./stealth.min.js")
  38. self.page = self.browser.new_page()
  39. def sure_playwright(self):
  40. if self.playwright is None:
  41. self.playwright = sync_playwright().start()
  42. def close(self):
  43. if self.page is not None:
  44. self.page.close()
  45. if self.browser is not None:
  46. self.browser.close()
  47. @abstractmethod
  48. def __get_name__(self):
  49. pass