如何用Selenium Java点击ng-click按钮?Web自动化测试代码求助
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 replaceBy.cssSelector()withBy.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:- By combined class names:
(Multiple classes are chained with dots, order doesn't matter as long as the button has all these classes)driver.findElement(By.cssSelector("button.sidebar-button.fa-bars")).click(); - By
ng-clickattribute:
Since the button's click is tied to theoffcanvasleft()function, this selector is super precise:driver.findElement(By.cssSelector("button[ng-click='offcanvasleft()']")).click();
- By combined class names:
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

