以下python代码,指挥谷歌浏览器登录deepseek后,自动输入问题,获得回复。供大家参考 from playwright.sync_api import sync_playwright, TimeoutError import time import os import json import sys
# 获取当前脚本的绝对路径 current_script_path = os.path.abspath(__file__) # 获取当前脚本所在的目录 current_script_dir = os.path.dirname(current_script_path)
# 构造存储路径 COOKIES_PATH = os.path.join(current_script_dir, 'storage_state.json') JIEGUO_PATH = os.path.join(current_script_dir, 'jieguo.txt') LOGIN_URL = "https://chat.deepseek.com/sign_in" CHAT_URL = "https://chat.deepseek.com"
def ask_deepseek(question): with sync_playwright() as p: # 浏览器配置参数 browser = p.chromium.launch( headless=not bool(int(sys.argv[1])), args=["--disable-blink-features=AutomationControlled"] )
# 尝试复用登录状态 context = None if os.path.exists(COOKIES_PATH): try: # 验证存储状态有效性 with open(COOKIES_PATH, "r") as f: state = json.load(f) if len(state.get("cookies", [])) == 0: raise Exception("Empty cookies")
# 创建带存储状态的上下文 context = browser.new_context( storage_state=COOKIES_PATH, user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", viewport={"width": 1920, "height": 1080} ) page = context.new_page() page.goto(CHAT_URL, wait_until="domcontentloaded")
# 检查登录状态是否有效 try: page.wait_for_selector("#chat-input", timeout=10000) print("成功复用登录状态") except TimeoutError: print("会话已过期,需要重新登录") os.remove(COOKIES_PATH) context.close() context = None except Exception as e: print(f"状态加载失败: {str(e)}") if context: context.close() context = None
# 需要重新登录的情况 if not context: context = browser.new_context() page = context.new_page() page.set_default_navigation_timeout(900000) page.set_default_timeout(900000)
# 执行登录流程457 page.goto(LOGIN_URL, wait_until="networkidle")
# 密码登录流程 try: page.locator("div.ds-tab__content:has-text('密码登录')").click(timeout=2000) #time.sleep(3) page.locator("input[placeholder='请输入手机号/邮箱地址']").click() #page.locator("input[placeholder='请输入手机号/邮箱地址']").fill("18634****") page.locator("input[placeholder='请输入手机号/邮箱地址']").type(sys.argv[2], delay=100) page.locator("input[placeholder='请输入密码']").click() page.locator("input[placeholder='请输入密码']").type(sys.argv[3],delay=200) #page.evaluate(""" # document.querySelector("input[placeholder='请输入手机号/邮箱地址']").value = "*****"; #""")
#page.locator("input[placeholder='请输入密码']").fill("******+") time.sleep(3) page.locator("div.ds-sign-up-form__register-button:has-text('登录')").click(timeout=2000) # 等待登录完成 page.wait_for_url("https://chat.deepseek.com/", timeout=95000) print("登录成功")
# 保存登录状态 context.storage_state(path=COOKIES_PATH) except Exception as e: print(f"登录失败: {str(e)}") raise
# 确保进入聊天界面 try: page.goto(CHAT_URL, wait_until="networkidle") page.wait_for_selector("#chat-input", timeout=10000) except TimeoutError: print("未能进入聊天界面") raise
# 开启联网搜索(每次询问都确保开启)
# 处理提问流程 try: # 输入问题 #print(page.content()) #with open(JIEGUO_PATH, 'w', encoding='utf-8') as file: # file.write(page.content()) #sys.exit(1) #page.locator("div.ds-button:has-text('联网搜索')").click(timeout=90000) buttons = page.locator("div[role='button']").all()
# 验证至少有2个按钮 if len(buttons) < 2: raise Exception("未找到足够的按钮")
# 获取第二个按钮(索引从0开始) second_button = buttons[1] #second_button.click() # 获取CSS变量值 #4c4c4c #4D6BFE text_color = second_button.evaluate(""" element => { return window.getComputedStyle(element) .getPropertyValue('--button-text-color') .trim(); } """)
if sys.argv[4]=='1': if text_color=='#4c4c4c': second_button.click() else: if text_color!='#4c4c4c': second_button.click() #page.locator("span:has-text('联网搜索')").click() page.locator("#chat-input").fill(question)
# 发送问题 page.keyboard.press("Enter")
# 智能等待回答完成 start_time = time.time() last_length = 0 stable_count = 0
while True: # 检测回答元素 <div class="ds-markdown ds-markdown--block" style="--ds-md-zoom: 1.143;"> answer_div = page.locator('div.ds-markdown.ds-markdown--block') current_text = answer_div.inner_text()
# 终止条件检测 if "【over】" in current_text: print("\n检测到终止标识") break
# 防卡死机制 if time.time() - start_time > 900: # 5分钟超时 print("\n响应超时") break
# 动态打印进度 new_length = len(current_text) if new_length > last_length: print(f"\r收到 {new_length} 字符...", end="") last_length = new_length stable_count = 0 else: stable_count += 1 if stable_count > 10: # 20秒无变化 print("\n响应中断") break
time.sleep(2)
# 获取最终答案 final_answer = answer_div.inner_text() return final_answer.replace("【ove888r】", "").strip()
finally: # 更新存储状态 context.storage_state(path=COOKIES_PATH) #context.close() #browser.close()
if __name__ == "__main__": # 带路径处理版
file_path = os.path.join(os.path.dirname(__file__), 'prompt.txt') if os.path.exists(file_path): with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: question = f.read() else: question = ""
jieguo=ask_deepseek(question) with open(JIEGUO_PATH, 'w', encoding='utf-8') as file: file.write(jieguo) print("运行结果已成功保存到 jieguo.txt 文件。")
|