You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright无法点击JanitorAI页面按钮 求技术帮助

解决Playwright在JanitorAI上的按钮点击问题

问题核心原因

你使用的css-h8nn2p这类以css-开头的类名是Chakra UI框架动态生成的,页面刷新或重载后可能会变化,导致选择器失效。此外,固定时长的time.sleep无法保证元素完全加载可交互,也是点击失败的常见原因。

针对性解决方案

1. 替换为稳定选择器

针对红色提示按钮(API not ready! Click to setup.)

用文本内容选择器替代动态类名,这是最可靠的方式:

# 方式1:文本精确匹配
page.click('text="API not ready! Click to setup."')

# 方式2:XPath文本匹配
page.click('//span[contains(text(), "API not ready! Click to setup.")]')

针对菜单按钮

利用元素的aria-haspopup属性或稳定类名(非动态生成的部分):

# 方式1:基于aria属性
page.click('button[aria-haspopup="menu"]')

# 方式2:基于稳定类名组合
page.click('button.chakra-menu__menu-button')

2. 替换不可靠的等待方式

去掉time.sleep(2),改用Playwright内置的等待机制,确保元素处于可交互状态:

# 等待红色按钮可见并可点击,再执行点击
page.wait_for_selector('text="API not ready! Click to setup."', state='visible')
page.click('text="API not ready! Click to setup."')

# 或者直接在click中设置等待(Playwright默认会等待元素可交互)
page.click('text="API not ready! Click to setup."', timeout=5000)

3. 强制点击(极端情况)

如果元素存在但被遮挡/不可见,可添加force=True参数强制触发点击事件:

page.click('text="API not ready! Click to setup."', force=True)

修改后的完整代码示例

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.firefox.launch(headless=False)
    page = browser.new_page()
    page.goto('https://www.janitorai.com/login')
    
    # 登录操作(保留原有选择器,后续若失效可改用id选择器)
    page.fill('#email', 'Censored for privacy reasons')
    page.fill('#password', 'Censored for privacy reasons')
    page.click('button[type="submit"].chakra-button')
    
    # 页面跳转操作,替换为稳定等待
    page.wait_for_selector('button.chakra-button.css-1nlwyv4', state='visible').click()
    page.click('.chakra-link.css-939ljh')
    
    # 等待聊天页面加载完成,替代time.sleep
    page.wait_for_load_state('networkidle')
    
    # 点击红色按钮
    page.click('text="API not ready! Click to setup."')
    
    print("Press the Enter key to close the browser...")
    input()
    browser.close()

额外排查点

  • 检查元素是否在iframe内:若按钮位于iframe中,需先切换到iframe再操作:
    iframe = page.frame_locator('iframe[src="xxx"]')
    iframe.click('text="API not ready! Click to setup."')
    
  • 检查页面是否有弹窗或遮挡元素:可通过page.screenshot(path='debug.png')截图查看元素状态。

内容的提问来源于stack exchange,提问作者Breath3Manually

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:05:20