bobocup commited on
Commit
7e7c823
·
verified ·
1 Parent(s): 14972fb

Create nb4x.py

Browse files
Files changed (1) hide show
  1. nb4x.py +341 -0
nb4x.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from selenium import webdriver
2
+ from selenium.webdriver.chrome.service import Service
3
+ from selenium.webdriver.chrome.options import Options
4
+ from selenium.webdriver.common.by import By
5
+ from selenium.webdriver.support.ui import WebDriverWait
6
+ from selenium.webdriver.support import expected_conditions as EC
7
+ from selenium.common.exceptions import TimeoutException
8
+ from selenium.webdriver.common.keys import Keys
9
+ from webdriver_manager.chrome import ChromeDriverManager
10
+ import time
11
+ import random
12
+ import string
13
+ import logging
14
+ import requests
15
+ import json
16
+ import re
17
+ import concurrent.futures
18
+ from concurrent.futures import ThreadPoolExecutor
19
+
20
+ # 配置日志
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format='%(asctime)s - %(levelname)s - %(message)s'
24
+ )
25
+ logger = logging.getLogger(__name__)
26
+
27
+ def get_verification_code(driver, email, max_retries=10, delay=2):
28
+ email_url = f'https://linshiyou.com/#/{email}'
29
+
30
+ # 打开新标签页并访问邮箱
31
+ driver.execute_script(f"window.open('{email_url}', '_blank')")
32
+ driver.switch_to.window(driver.window_handles[-1])
33
+ logger.info("已打开邮箱页面")
34
+
35
+ for _ in range(max_retries):
36
+ try:
37
+ # 刷新页面
38
+ driver.refresh()
39
+ time.sleep(2)
40
+
41
+ # 直接获取包含验证码的div元素的内容
42
+ body_content = driver.find_element(By.CLASS_NAME, "body").get_attribute('outerHTML')
43
+ logger.info(f"获取到邮件内容: {body_content}")
44
+
45
+ # 使用正则表达式匹配6位数字验证码
46
+ match = re.search(r'\b\d{6}\b', body_content)
47
+ if match:
48
+ verification_code = match.group(0)
49
+ logger.info(f"获取到验证码: {verification_code}")
50
+
51
+ # 关闭邮箱标签页
52
+ driver.close()
53
+ driver.switch_to.window(driver.window_handles[0])
54
+
55
+ return verification_code
56
+
57
+ except Exception as e:
58
+ logger.error(f"获取验证码时发生错误: {str(e)}")
59
+
60
+ time.sleep(delay)
61
+ logger.info(f"等待验证码,重试第 {_ + 1} 次")
62
+
63
+ # 如果获取失败,确保回到主标签页
64
+ try:
65
+ driver.close()
66
+ driver.switch_to.window(driver.window_handles[0])
67
+ except:
68
+ pass
69
+
70
+ logger.error("未能获取到验证码")
71
+ return None
72
+
73
+ def get_cookie(driver):
74
+ try:
75
+ cookie_script = """
76
+ var cookieString = document.cookie;
77
+ var essentialCookies = cookieString.split('; ').filter(function(cookie) {
78
+ return cookie.startsWith('daily_query_') ||
79
+ cookie.startsWith('DSR=') ||
80
+ cookie.startsWith('DS=') ||
81
+ cookie.startsWith('uuid_guest=') ||
82
+ cookie.startsWith('ai_model=');
83
+ }).join('; ');
84
+ console.log('Essential Cookies:', essentialCookies);
85
+ return essentialCookies;
86
+ """
87
+ cookie = driver.execute_script(cookie_script)
88
+
89
+ logger.info(f"获取的 Cookie: {cookie}")
90
+
91
+ # 将cookie发送到API服务
92
+ try:
93
+ response = requests.post(
94
+ 'http://localhost:7860/cookies',
95
+ json={"cookie": cookie},
96
+ timeout=5
97
+ )
98
+ if response.status_code == 200:
99
+ logger.info("Cookie已成功保存到API服务")
100
+ else:
101
+ logger.error("保存Cookie到API服务失败")
102
+ except Exception as e:
103
+ logger.error(f"发送Cookie到API服务时出错: {str(e)}")
104
+
105
+ return cookie
106
+ except Exception as e:
107
+ logger.error(f"获取cookie错误: {str(e)}")
108
+ return None
109
+
110
+ def wait_for_url(driver, url, timeout=10):
111
+ try:
112
+ start_time = time.time()
113
+ while time.time() - start_time < timeout:
114
+ current_url = driver.current_url.rstrip('/')
115
+ target_url = url.rstrip('/')
116
+ if current_url == target_url:
117
+ return True
118
+ time.sleep(0.5)
119
+ return False
120
+ except TimeoutException:
121
+ return False
122
+
123
+ def wait_for_email_input(driver, timeout=10):
124
+ """等待邮箱输入框出现并返回"""
125
+ start_time = time.time()
126
+ while time.time() - start_time < timeout:
127
+ try:
128
+ input_js = """
129
+ return document.querySelector("#AppProvider_Wrapper > form > descope-wc")
130
+ .shadowRoot.querySelector("#TExZpnv5m6")
131
+ .shadowRoot.querySelector("#input-vaadin-email-field-3")
132
+ """
133
+ email_input = driver.execute_script(input_js)
134
+ if email_input:
135
+ logger.info("邮箱输入框已加载")
136
+ return True
137
+ except Exception:
138
+ pass
139
+ time.sleep(0.5)
140
+ logger.error("邮箱输入框未出现")
141
+ return False
142
+
143
+ def input_email(driver, email):
144
+ """使用JavaScript输入邮箱"""
145
+ try:
146
+ input_js = f"""
147
+ var input = document.querySelector("#AppProvider_Wrapper > form > descope-wc")
148
+ .shadowRoot.querySelector("#TExZpnv5m6")
149
+ .shadowRoot.querySelector("#input-vaadin-email-field-3");
150
+ input.value = "{email}";
151
+ input.dispatchEvent(new Event('input', {{ bubbles: true }}));
152
+ input.dispatchEvent(new Event('change', {{ bubbles: true }}));
153
+ """
154
+ driver.execute_script(input_js)
155
+ logger.info("输入邮箱成功")
156
+ return True
157
+ except Exception as e:
158
+ logger.error(f"输入邮箱失败: {str(e)}")
159
+ return False
160
+
161
+ def input_verification_code(driver, code):
162
+ """使用JavaScript输入验证码"""
163
+ try:
164
+ input_js = f"""
165
+ var input = document.querySelector("#AppProvider_Wrapper > form > descope-wc")
166
+ .shadowRoot.querySelector("#oneTimeCodeId")
167
+ .shadowRoot.querySelector("#input-vaadin-text-field-7 > div.wrapper > descope-text-field:nth-child(1)")
168
+ .shadowRoot.querySelector("#input-vaadin-text-field-35");
169
+ input.value = "{code}";
170
+ input.dispatchEvent(new Event('input', {{ bubbles: true }}));
171
+ input.dispatchEvent(new Event('change', {{ bubbles: true }}));
172
+ """
173
+ driver.execute_script(input_js)
174
+ logger.info("输入验证码成功")
175
+ return True
176
+ except Exception as e:
177
+ logger.error(f"输入验证码失败: {str(e)}")
178
+ return False
179
+
180
+ def registration_process(driver, wait):
181
+ try:
182
+ # 生成邮箱地址
183
+ email = generate_email()
184
+ if not email:
185
+ logger.error("生成邮箱失败")
186
+ return False
187
+
188
+ # 第一步:打开认证页面
189
+ driver.get("https://you.com/authenticate")
190
+ logger.info("打开认证页面")
191
+
192
+ # 等待邮箱输入框出现并输入邮箱
193
+ if not wait_for_email_input(driver):
194
+ logger.error("等待邮箱输入框超时")
195
+ return False
196
+
197
+ if not input_email(driver, email):
198
+ logger.error("输入邮箱失败")
199
+ return False
200
+
201
+ time.sleep(0.5)
202
+
203
+ # 按回车继续
204
+ actions = webdriver.ActionChains(driver)
205
+ actions.send_keys(Keys.RETURN)
206
+ actions.perform()
207
+ logger.info("按下回车键")
208
+ time.sleep(2)
209
+
210
+ # 获取验证码
211
+ verification_code = get_verification_code(driver, email)
212
+ if not verification_code:
213
+ logger.error("获取验证码失败")
214
+ return False
215
+
216
+ # 输入验证码
217
+ if not input_verification_code(driver, verification_code):
218
+ logger.error("输入验证码失败")
219
+ return False
220
+
221
+ time.sleep(2)
222
+
223
+ # 等待URL变化并获取cookie
224
+ if wait_for_url(driver, "https://you.com"):
225
+ logger.info("URL已变更为 https://you.com")
226
+ time.sleep(1)
227
+ cookie = get_cookie(driver)
228
+ if cookie:
229
+ logger.info("成功获取cookie")
230
+ return True
231
+ else:
232
+ logger.error("获取cookie失败")
233
+ return False
234
+ else:
235
+ logger.error("URL未变化为预期值")
236
+ return False
237
+
238
+ except Exception as e:
239
+ logger.error(f"注册过程错误: {str(e)}")
240
+ return False
241
+
242
+ def single_registration():
243
+ # 创建Chrome选项
244
+ chrome_options = Options()
245
+ chrome_options.add_argument('--no-sandbox')
246
+ chrome_options.add_argument('--disable-dev-shm-usage')
247
+ chrome_options.add_argument('--disable-gpu')
248
+
249
+ # 使用半无头模式
250
+ chrome_options.add_argument('--window-position=-32000,-32000') # 将窗口移到屏幕外
251
+ # chrome_options.add_argument('--headless=new') # 注释掉完全无头模式
252
+
253
+ # 其他优化选项
254
+ chrome_options.add_argument('--start-maximized')
255
+ chrome_options.add_argument('--disable-blink-features=AutomationControlled')
256
+ chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
257
+ chrome_options.add_experimental_option('useAutomationExtension', False)
258
+
259
+ # 创建ChromeDriver服务和实例
260
+ service = Service(ChromeDriverManager().install())
261
+ driver = webdriver.Chrome(service=service, options=chrome_options)
262
+ wait = WebDriverWait(driver, 20)
263
+
264
+ try:
265
+ success = registration_process(driver, wait)
266
+ if success:
267
+ logger.info("注册成功")
268
+ else:
269
+ logger.error("注册失败")
270
+ return success
271
+ except Exception as e:
272
+ logger.error(f"注册过程发生错误: {str(e)}")
273
+ return False
274
+ finally:
275
+ driver.quit()
276
+
277
+ def worker(thread_id):
278
+ error_count = 0
279
+ while True:
280
+ try:
281
+ logger.info(f"线程 {thread_id}: 开始新的注册循环")
282
+ success = single_registration()
283
+
284
+ if success:
285
+ error_count = 0
286
+ logger.info(f"线程 {thread_id}: 本次循环成功")
287
+ else:
288
+ error_count += 1
289
+ logger.error(f"线程 {thread_id}: 本次循环失败,这是第 {error_count} 次失败")
290
+
291
+ if error_count >= 5:
292
+ logger.critical(f"线程 {thread_id}: 续 {error_count} 次失败,退出线程")
293
+ break
294
+
295
+ if not success:
296
+ logger.info(f"线程 {thread_id}: 等待5秒后重试")
297
+ time.sleep(5)
298
+
299
+ except Exception as e:
300
+ logger.error(f"线程 {thread_id} 发生错误: {str(e)}")
301
+ error_count += 1
302
+ if error_count >= 5:
303
+ break
304
+
305
+ def main():
306
+ try:
307
+ # 获取用户输入的并发数
308
+ while True:
309
+ try:
310
+ concurrent_num = int(input("请输入需要的并发数(1-10): "))
311
+ if 1 <= concurrent_num <= 10:
312
+ break
313
+ else:
314
+ print("请输入1-10之间的数字")
315
+ except ValueError:
316
+ print("请输入有效的数字")
317
+
318
+ logger.info(f"启动 {concurrent_num} 个并发线程")
319
+
320
+ # 创建线程池
321
+ with ThreadPoolExecutor(max_workers=concurrent_num) as executor:
322
+ # 提交任务
323
+ futures = [executor.submit(worker, i+1) for i in range(concurrent_num)]
324
+
325
+ # 等待所有任务完成
326
+ concurrent.futures.wait(futures)
327
+
328
+ except KeyboardInterrupt:
329
+ logger.info("程序被用户中断")
330
+ except Exception as e:
331
+ logger.error(f"主程序异常: {str(e)}")
332
+ finally:
333
+ logger.info("程序结束")
334
+
335
+ def generate_email():
336
+ """生成随机邮箱地址"""
337
+ random_prefix = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
338
+ return f"{random_prefix}@youxiang.dev"
339
+
340
+ if __name__ == "__main__":
341
+ main()