main.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import time
  4. import subprocess
  5. import sys
  6. import asyncio
  7. import httpx
  8. GO_TO_URL = 'https://sepolia-faucet.pk910.de/'
  9. # 是否使用代理, 是 True 否 False
  10. USE_PROXY = True
  11. # 是否无头模式, 是 True 否 False
  12. HEADLESS = False
  13. # 是否记录用户数据, 例如cookies, 是 True 否 False
  14. NEED_USER_DATA = False
  15. class GotifySender:
  16. def __init__(self, url, token='A0Xg6ZE5946iBYg'):
  17. self.url = url + f"?token={token}"
  18. async def send_message(self, title='测试标题', message='测试消息', priority=5):
  19. data = {
  20. "message": message,
  21. "title": title,
  22. "priority": priority
  23. }
  24. async with httpx.AsyncClient() as client:
  25. try:
  26. response = await client.post(self.url, json=data)
  27. if response.status_code == 200:
  28. print("消息发送成功")
  29. else:
  30. print(f"消息发送失败,状态码: {response.status_code}")
  31. except httpx.RequestException as e:
  32. print(f"请求出现异常: {e}")
  33. class ExecuteBrowserActon(object):
  34. def click_elements(self, page): # 点击元素
  35. pass
  36. def check_elements(self, page): # 检查元素
  37. pass
  38. def scroll_page(self): # 滚动页面
  39. pass
  40. class BrowserAutomation:
  41. def __init__(self):
  42. self.use_proxy = USE_PROXY
  43. self.headless = HEADLESS
  44. self.need_user_data = NEED_USER_DATA
  45. self.go_to_url = GO_TO_URL if GO_TO_URL else 'about:blank'
  46. self.http = 'http://'
  47. self.proxy_addr = 'http://127.0.0.1:7890'
  48. self.target_url = self.go_to_url if 'http' in self.go_to_url else self.http + self.go_to_url
  49. self.user_data_dir = os.path.join(
  50. self.get_current_file_path(),
  51. 'user_data')
  52. def hang_up_browser(self, page): # 挂起浏览器
  53. try:
  54. while True:
  55. page.query_selector("head").inner_html()
  56. time.sleep(1)
  57. except Exception as e:
  58. print(f"浏览器被关闭或发生异常: {e}")
  59. print('关闭浏览器')
  60. def set_browser(self, playwright): # 设置浏览器
  61. if self.need_user_data:
  62. if self.use_proxy:
  63. browser = playwright.chromium.launch_persistent_context(
  64. self.user_data_dir,
  65. proxy={"server": self.proxy_addr},
  66. headless=self.headless,
  67. args=['--start-maximized'],
  68. no_viewport=True,
  69. bypass_csp=True, # 允许跨站脚本
  70. locale='zh-CN', # 设置浏览器语言为中文
  71. # 设置 user-agent
  72. user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36'
  73. )
  74. else:
  75. browser = playwright.chromium.launch_persistent_context(
  76. self.user_data_dir,
  77. headless=self.headless,
  78. args=['--start-maximized'],
  79. no_viewport=True,
  80. bypass_csp=True, # 允许跨站脚本
  81. locale='zh-CN', # 设置浏览器语言为中文
  82. # 设置 user-agent
  83. user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36'
  84. )
  85. else:
  86. if self.use_proxy:
  87. browser = playwright.chromium.launch(
  88. proxy={"server": self.proxy_addr},
  89. headless=self.headless,
  90. args=['--start-maximized']
  91. )
  92. else:
  93. browser = playwright.chromium.launch(
  94. headless=self.headless,
  95. args=['--start-maximized']
  96. )
  97. print('打开浏览器')
  98. return browser
  99. def get_current_file_path(self): # 获取当前文件路径
  100. return os.path.dirname(os.path.abspath(__file__))
  101. def exce_browser_action(self, page):
  102. # 实例化执行浏览器动作类
  103. Exce = ExecuteBrowserActon()
  104. # 模拟各种动作
  105. def open_browser(self): # 打开浏览器
  106. with sync_playwright() as playwright:
  107. browser = self.set_browser(playwright)
  108. if self.need_user_data:
  109. page = browser.pages[0]
  110. else:
  111. context = browser.new_context(no_viewport=True)
  112. page = context.new_page()
  113. page.goto(self.target_url)
  114. # TODO 此处开始执行自动化逻辑
  115. self.exce_browser_action(page)
  116. # 自动化执行完成, 挂起浏览器挂机,
  117. self.hang_up_browser(page)
  118. browser.close()
  119. def main(self):
  120. if self.need_user_data:
  121. if not os.path.exists(self.user_data_dir):
  122. os.mkdir(self.user_data_dir)
  123. self.open_browser()
  124. if __name__ == '__main__':
  125. try:
  126. from playwright.sync_api import sync_playwright
  127. except ImportError:
  128. print('playwright 未安装, 正在安装...')
  129. subprocess.check_call(
  130. [sys.executable, "-m", "pip", "install", "playwright"])
  131. time.sleep(1)
  132. # 这里要执行终端命令, playwright install
  133. subprocess.check_call([sys.executable, "-m", "playwright", "install"])
  134. time.sleep(1)
  135. subprocess.check_call(
  136. [sys.executable, "-m", "playwright", "install-deps"])
  137. print("playwright 安装完成,正在重新运行程序...")
  138. subprocess.check_call([sys.executable, __file__])
  139. B = BrowserAutomation()
  140. B.main()