使用Java ui4j无法定位登录提交按钮问题求助
Hey there, let's get that login button working for you! The problem in your code is how you're targeting the button—your selector syntax is incorrect, which is why you're getting a NULL element.
What Went Wrong
Your current line:
doc.query("sc-gZMcBi btn btn-primary jcDsfy").focus().click();
This doesn't work because:
- Class selectors in CSS require a dot (
.) prefix. Without it, the browser doesn't recognize these as class names. - You're using
btnas an element type, which isn't valid—you need to specify the actual HTML element:button.
Correct Locator Options
Here are several reliable ways to target the login button:
- Proper Full Class Selector
Combine all classes with dots and specify thebuttonelement:
doc.query("button.sc-gZMcBi.btn.btn-primary.jcDsfy").focus().click();
- Use a Unique Generated Class
ThejcDsfyclass looks like a React-generated unique class (unlikely to be used elsewhere on the page). This simplifies the selector a lot:
doc.query("button.jcDsfy").focus().click();
- Target by
type="submit"
Since it's the only submit button in the form, this is a clean, reliable option:
doc.query("button[type='submit']").focus().click();
- Narrow Down with Parent Form
If there are multiple forms on the page, use the form's class to be more specific:
doc.query("form.sc-iwsKbI.ehzITl button[type='submit']").focus().click();
Updated Full Code Example
Replace your last line with one of the options above. Here's the full fixed code using the unique class approach:
doc.query("input[id='usr']").setValue("xxxx"); try { Thread.sleep(2000); } catch (InterruptedException ex) { } doc.query("input[id='pwd']").setValue("yyyyyy"); try { Thread.sleep(2000); } catch (InterruptedException ex) { } doc.query("button.jcDsfy").focus().click();
Bonus Tip: Avoid Fixed Sleeps (If Possible)
Instead of using Thread.sleep(), consider waiting for the button to be present/interactable (depending on your testing framework). This makes your code more robust for dynamic pages. For example, if you're using Selenium, you'd use a WebDriverWait with ExpectedConditions.elementToBeClickable().
内容的提问来源于stack exchange,提问作者Jon Osterman

