__init__.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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, account: str, playwright=None):
  10. api.assert_not_none(account, "账号不能为空")
  11. self.account = account
  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, playwright):
  20. if playwright:
  21. self.playwright = playwright
  22. else:
  23. self.playwright = sync_playwright().start()
  24. self.browser = self.playwright.chromium.launch_persistent_context(
  25. proxy=None,
  26. user_data_dir=f'.{SPLIT_CHAR}.data{SPLIT_CHAR}{self.__get_name__()}{SPLIT_CHAR}{self.account}',
  27. headless=False,
  28. slow_mo=1000,
  29. channel="chrome",
  30. ignore_https_errors=True,
  31. user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
  32. 'Chrome/126.0.0.0 Safari/537.36',
  33. args=[
  34. '--disable-blink-features=AutomationControlled',
  35. # '--incognito',
  36. '--ignore-certificate-errors-spki-list',
  37. '--disable-web-security', # 禁用 Web 安全性,类似于 ChromeOptions 中的 --ignore-certificate-errors-spki-list
  38. '--no-sandbox', # 禁用沙盒模式
  39. '--disable-dev-shm-usage', # 禁用/dev/shm使用
  40. '--disable-features=site-per-process', # 禁用每个站点的进程,类似于 ChromeOptions 中的 --no-sandbox
  41. '--ignore-certificate-errors', # 忽略证书错误
  42. '--disable-features=AutomationControlled' # 禁用与自动化相关的特性
  43. ])
  44. self.browser.add_init_script(path="./stealth.min.js")
  45. self.page = self.browser.pages[0]
  46. def close(self):
  47. self.browser.close()
  48. self.playwright.stop()
  49. @abstractmethod
  50. def __get_name__(self):
  51. pass