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

如何用Selenium Java点击ng-click按钮?Web自动化测试代码求助

Fixing Your Web Automation Click Issue

Hey Chris, let's break down why your click command isn't doing anything and get it sorted out!

The Core Problem

First off, you're using By.cssSelector() but passing an XPath expression as the argument—those are two totally different selector syntaxes, so Selenium doesn't know how to interpret that. That's the main reason your code has no effect.

Solutions to Try

  • Switch to XPath selector if you want to use your original path
    Just replace By.cssSelector() with By.xpath(). Also, using single quotes around your XPath string can avoid messy double-quote escaping:

    driver.findElement(By.xpath('//*[@id="mainrow"]/div/div/button[1]')).click();
    
  • Use CSS Selectors (more efficient for this case)
    Your target button has unique attributes we can leverage for a more reliable CSS selector:

    1. By combined class names:
      driver.findElement(By.cssSelector("button.sidebar-button.fa-bars")).click();
      
      (Multiple classes are chained with dots, order doesn't matter as long as the button has all these classes)
    2. By ng-click attribute:
      Since the button's click is tied to the offcanvasleft() function, this selector is super precise:
      driver.findElement(By.cssSelector("button[ng-click='offcanvasleft()']")).click();
      
  • Add Explicit Wait (to avoid timing issues)
    Sometimes clicks fail because the element isn't fully loaded or clickable yet. Adding an explicit wait ensures Selenium waits until the button is ready:

    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement sidebarButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[ng-click='offcanvasleft()']")));
    sidebarButton.click();
    

Give these a shot—one of them should get that sidebar button working!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:19:41