Selenium点击提交按钮失败求助:正确实现账户创建按钮定位的代码方案
Hey Brendan, the issue with your current code is that the By.className() method only accepts a single class name—you can’t pass multiple space-separated classes like you did. That’s why your selector isn’t finding the button. Let’s go through a few reliable ways to fix this:
Option 1: Use CSS Selector (Most Recommended)
CSS selectors let you combine multiple classes or target specific attributes for precise element matching. Since your button has a unique-looking class t-auth__login--btn, you can use that directly for simplicity:
driver.findElement(By.cssSelector(".t-auth__login--btn")).click();
If you want to make it more explicit (to avoid conflicts with any other elements), combine the class with the button type:
driver.findElement(By.cssSelector("button[type='submit'].t-auth__login--btn")).click();
Or use all the classes together (note the lack of spaces between class names in CSS syntax):
driver.findElement(By.cssSelector("button.btn.btn--stretch.btn--primary.btn--green.t-auth__login--btn")).click();
Option 2: Use XPath Selector
XPath is flexible if you prefer targeting the button’s text or a combination of attributes:
- By exact button text:
driver.findElement(By.xpath("//button[text()='Create my account']")).click();
- By type and class combination:
driver.findElement(By.xpath("//button[@type='submit' and contains(@class, 'btn--green')]")).click();
Bonus: Add Wait for Element Interactivity
Sometimes the button might not be immediately clickable due to page loading delays. Using WebDriverWait ensures you only click once the element is fully ready:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; // Wait up to 10 seconds for the button to be clickable WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".t-auth__login--btn"))).click();
Any of these methods should work reliably for your "Create my account" button. Start with the simplest CSS selector using the unique class—it’s the most maintainable option!
内容的提问来源于stack exchange,提问作者Brendan Ahern

