VBA Selenium中无法点击嵌套Span结构按钮的技术求助
Let's break down why your original code wasn't working and fix it step by step!
What Was Wrong with Your Original Code?
Your XPath had two critical issues:
- Incorrect Attribute Reference: You used
contains(@span, ...)butspanis an HTML tag, not an attribute. To target text inside a span, you need to reference the element's text content withtext(). - Typo: You wrote
Create Detalinstead ofCreate Detail—that small misspelling would prevent the XPath from matching any element.
Working Solutions to Click the Button
Here are a few reliable ways to trigger the click action:
1. Target the Button Directly via Class
Since the button has a distinct class click-primary, this is the most straightforward and reliable approach:
Obj.FindElement(By.XPath, "//button[contains(@class, 'click-primary')]").Click
Or use a CSS selector for a more concise syntax:
Obj.FindElement(By.CssSelector, "button.btn.click-primary").Click
2. Target the Span Text and Navigate to Its Parent Button
If you prefer to use the span's visible text for targeting, locate the span first then select its parent button element:
Obj.FindElement(By.XPath, "//span[text()='Create Detail']/parent::button").Click
Alternatively, you can click the span directly (though clicking the button itself is more consistent for most UI setups):
Obj.FindElement(By.XPath, "//span[text()='Create Detail']").Click
3. Add a Wait for Element Load (If Needed)
Sometimes the button isn't fully loaded when your code runs. Add a wait to ensure the element is present before attempting to click:
' Wait up to 10 seconds for the button to appear Obj.Wait 10000 Obj.FindElement(By.XPath, "//button[contains(@class, 'click-primary')]").Click
Quick Notes
- Ensure your automation object (
Obj) is properly initialized (e.g., Selenium ChromeDriver, IE DOM object). - Double-check for typos in element text or attributes—small errors like missing letters will break your selector.
内容的提问来源于stack exchange,提问作者Zenik

