StarrySkyWorld commited on
Commit
dc41b5b
·
verified ·
1 Parent(s): 845416d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +39 -16
main.py CHANGED
@@ -32,7 +32,6 @@ def load_cookies():
32
 
33
  converted_cookies = []
34
  for cookie in raw_cookies:
35
- # 构建Playwright兼容的cookie格式
36
  new_cookie = {
37
  "name": cookie.get("name"),
38
  "value": cookie.get("value"),
@@ -40,13 +39,11 @@ def load_cookies():
40
  "path": cookie.get("path", "/"),
41
  }
42
 
43
- # 处理过期时间:expirationDate -> expires (秒转为秒,Playwright接受Unix时间戳)
44
  if "expirationDate" in cookie:
45
  new_cookie["expires"] = cookie["expirationDate"]
46
  elif "expires" in cookie:
47
  new_cookie["expires"] = cookie["expires"]
48
 
49
- # 处理sameSite:转换为Playwright格式
50
  same_site = cookie.get("sameSite", "").lower()
51
  if same_site in ["strict", "lax", "none"]:
52
  new_cookie["sameSite"] = same_site.capitalize()
@@ -55,13 +52,11 @@ def load_cookies():
55
  elif same_site == "unspecified" or same_site == "no_restriction":
56
  new_cookie["sameSite"] = "None"
57
  else:
58
- new_cookie["sameSite"] = "Lax" # 默认值
59
 
60
- # 处理secure和httpOnly
61
  new_cookie["secure"] = cookie.get("secure", False)
62
  new_cookie["httpOnly"] = cookie.get("httpOnly", False)
63
 
64
- # sameSite=None时必须secure=True
65
  if new_cookie["sameSite"] == "None":
66
  new_cookie["secure"] = True
67
 
@@ -79,6 +74,36 @@ async def activate_task():
79
  except Exception as e:
80
  print(f"[Activate] Error: {e}")
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  async def init_browser():
83
  """初始化浏览器"""
84
  global browser, page, context, config
@@ -93,13 +118,10 @@ async def init_browser():
93
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
94
  )
95
 
96
- # 按域名分组导入cookies
97
  if cookies:
98
- # 过滤有效的cookies
99
  valid_cookies = []
100
  for cookie in cookies:
101
  try:
102
- # 确保必要字段存在
103
  if cookie.get("name") and cookie.get("value") and cookie.get("domain"):
104
  valid_cookies.append(cookie)
105
  except Exception as e:
@@ -111,7 +133,6 @@ async def init_browser():
111
  print(f"[Browser] Loaded {len(valid_cookies)} cookies")
112
  except Exception as e:
113
  print(f"[Browser] Error loading cookies: {e}")
114
- # 尝试逐个添加
115
  success_count = 0
116
  for cookie in valid_cookies:
117
  try:
@@ -123,7 +144,6 @@ async def init_browser():
123
 
124
  page = await context.new_page()
125
 
126
- # 打开目标页面
127
  target_link = config.get("targetLink", "https://www.example.com")
128
  try:
129
  await page.goto(target_link, wait_until="networkidle", timeout=60000)
@@ -140,19 +160,22 @@ async def close_browser():
140
  @asynccontextmanager
141
  async def lifespan(app: FastAPI):
142
  """应用生命周期管理"""
143
- # 启动时
144
  await init_browser()
145
 
146
- # 启动定时任务
147
  if config and config.get("activateLink"):
148
  interval = config.get("activateInterval", 60)
149
  scheduler.add_job(activate_task, "interval", seconds=interval)
150
- scheduler.start()
151
- print(f"[Scheduler] Started with interval: {interval}s")
 
 
 
 
 
152
 
153
  yield
154
 
155
- # 关闭时
156
  scheduler.shutdown(wait=False)
157
  await close_browser()
158
 
 
32
 
33
  converted_cookies = []
34
  for cookie in raw_cookies:
 
35
  new_cookie = {
36
  "name": cookie.get("name"),
37
  "value": cookie.get("value"),
 
39
  "path": cookie.get("path", "/"),
40
  }
41
 
 
42
  if "expirationDate" in cookie:
43
  new_cookie["expires"] = cookie["expirationDate"]
44
  elif "expires" in cookie:
45
  new_cookie["expires"] = cookie["expires"]
46
 
 
47
  same_site = cookie.get("sameSite", "").lower()
48
  if same_site in ["strict", "lax", "none"]:
49
  new_cookie["sameSite"] = same_site.capitalize()
 
52
  elif same_site == "unspecified" or same_site == "no_restriction":
53
  new_cookie["sameSite"] = "None"
54
  else:
55
+ new_cookie["sameSite"] = "Lax"
56
 
 
57
  new_cookie["secure"] = cookie.get("secure", False)
58
  new_cookie["httpOnly"] = cookie.get("httpOnly", False)
59
 
 
60
  if new_cookie["sameSite"] == "None":
61
  new_cookie["secure"] = True
62
 
 
74
  except Exception as e:
75
  print(f"[Activate] Error: {e}")
76
 
77
+ async def auto_click_task():
78
+ """自动点击 'Got it' 按钮"""
79
+ global page
80
+ if not page:
81
+ return
82
+
83
+ try:
84
+ # 查找包含 "Got it" 文本的按钮
85
+ selectors = [
86
+ 'button:has-text("Got it")',
87
+ 'a:has-text("Got it")',
88
+ '[role="button"]:has-text("Got it")',
89
+ 'input[type="button"][value="Got it"]',
90
+ 'input[type="submit"][value="Got it"]',
91
+ ]
92
+
93
+ for selector in selectors:
94
+ try:
95
+ element = page.locator(selector).first
96
+ if await element.is_visible(timeout=500):
97
+ await element.click()
98
+ print(f'[AutoClick] Clicked "Got it" button')
99
+ return
100
+ except:
101
+ continue
102
+
103
+ except Exception as e:
104
+ # 静默处理,避免日志刷屏
105
+ pass
106
+
107
  async def init_browser():
108
  """初始化浏览器"""
109
  global browser, page, context, config
 
118
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
119
  )
120
 
 
121
  if cookies:
 
122
  valid_cookies = []
123
  for cookie in cookies:
124
  try:
 
125
  if cookie.get("name") and cookie.get("value") and cookie.get("domain"):
126
  valid_cookies.append(cookie)
127
  except Exception as e:
 
133
  print(f"[Browser] Loaded {len(valid_cookies)} cookies")
134
  except Exception as e:
135
  print(f"[Browser] Error loading cookies: {e}")
 
136
  success_count = 0
137
  for cookie in valid_cookies:
138
  try:
 
144
 
145
  page = await context.new_page()
146
 
 
147
  target_link = config.get("targetLink", "https://www.example.com")
148
  try:
149
  await page.goto(target_link, wait_until="networkidle", timeout=60000)
 
160
  @asynccontextmanager
161
  async def lifespan(app: FastAPI):
162
  """应用生命周期管理"""
 
163
  await init_browser()
164
 
165
+ # 定时激活任务
166
  if config and config.get("activateLink"):
167
  interval = config.get("activateInterval", 60)
168
  scheduler.add_job(activate_task, "interval", seconds=interval)
169
+ print(f"[Scheduler] Activate task started with interval: {interval}s")
170
+
171
+ # 自动点击 "Got it" 按钮任务
172
+ scheduler.add_job(auto_click_task, "interval", seconds=5)
173
+ print(f"[Scheduler] Auto-click task started with interval: 5s")
174
+
175
+ scheduler.start()
176
 
177
  yield
178
 
 
179
  scheduler.shutdown(wait=False)
180
  await close_browser()
181