Selenium获取特定span元素innerHTML值异常问题咨询
I’ve run into similar flaky element-location issues with Selenium before, so let’s break down why your value fetching is inconsistent and how to fix it:
1. You’re Targeting the Wrong .robux Element
The By.ClassName("robux") selector grabs the first element on the page with that class. If there are other elements (like user balance, pending funds, etc.) using the same .robux class, you’ll randomly pull those values instead of the group funds.
Fix this by using a more precise selector that ties the .robux span to its parent container:
- CSS Selector:
driver.FindElement(By.CssSelector("#ctl00_cphRoblox_rbxGroupFundsPane_GroupFunds .robux")).GetAttribute("innerHTML") - XPath:
driver.FindElement(By.XPath("//div[@id='ctl00_cphRoblox_rbxGroupFundsPane_GroupFunds']//span[@class='robux']")).GetAttribute("innerHTML")
Both target only the .robux element inside the specific group funds box, eliminating cross-contamination from other elements.
2. The Page/Element Isn’t Fully Loaded Yet
Selenium might be grabbing the element before its dynamic content (the Robux number) finishes loading. This leads to stale or incorrect values.
Use an explicit wait to ensure the element is ready and contains valid numeric text:
using OpenQA.Selenium.Support.UI; using System; // Wait up to 10 seconds for the element to be ready var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); var robuxElement = wait.Until(driver => { var elem = driver.FindElement(By.CssSelector("#ctl00_cphRoblox_rbxGroupFundsPane_GroupFunds .robux")); // Only return the element if it has non-empty, numeric text return !string.IsNullOrEmpty(elem.Text) && int.TryParse(elem.Text, out _) ? elem : null; }); string robuxValue = robuxElement.Text; dcWeb.SendMessage(s + " = Pending and Robux: " + robuxValue);
This waits until the element’s text is a valid number, so you don’t grab unloaded or placeholder content.
3. Debug to Confirm Your Target
If you’re still having issues, add a quick debug step to verify you’re targeting the right element:
var groupFundsContainer = driver.FindElement(By.Id("ctl00_cphRoblox_rbxGroupFundsPane_GroupFunds")); Console.WriteLine("Container content: " + groupFundsContainer.Text);
This prints the full text of the funds box (e.g., "Funds: 128") so you can confirm the value is present before extracting it.
内容的提问来源于stack exchange,提问作者jake yancey

