如何用Java-Selenium WebDriver获取AngularJS ng-repeat元素索引
To figure out how many elements are generated by data-ng-repeat="assessment in assessmentData" in your AngularJS app, here's a straightforward, reliable approach using Selenium WebDriver:
Step 1: Wait for Dynamic Content to Load
AngularJS renders elements dynamically, so first we need to make sure all the ng-repeat elements have loaded before we try to count them. Using an explicit wait avoids race conditions where Selenium might try to count elements before they’re ready.
Step 2: Locate All ng-repeat Elements
Target all elements with the data-ng-repeat attribute matching your expression. You can use either XPath or CSS selector—pick whichever works best for your setup.
Step 3: Get the Total Count
Once you’ve grabbed the list of elements, just get the size of that list to get the total number of questions/items.
Java Code Examples
Using XPath (your preferred method):
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.List; // Initialize your WebDriver (e.g., ChromeDriver) WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Wait until all ng-repeat elements are present in the DOM List<WebElement> assessmentElements = wait.until( ExpectedConditions.presenceOfAllElementsLocatedBy( By.xpath("//div[@data-ng-repeat='assessment in assessmentData']") ) ); // Get the total count int totalQuestions = assessmentElements.size(); System.out.println("Total number of quiz questions: " + totalQuestions);
Using CSS Selector (alternative option):
If you want to switch to CSS, use this locator instead of the XPath:
By.cssSelector("div[data-ng-repeat='assessment in assessmentData']")
Advanced Option: Access Angular Scope Directly
If you want to bypass the DOM and get the count straight from Angular’s assessmentData array, you can execute JavaScript in the browser. Note this works only if the app’s scope is accessible (may not work for isolated scopes):
Long totalQuestions = (Long) ((JavascriptExecutor) driver).executeScript( "return angular.element(document.querySelector('[data-ng-repeat=\"assessment in assessmentData\"]')).scope().assessmentData.length;" ); System.out.println("Total number of quiz questions: " + totalQuestions);
Quick Tips
- Avoid
Thread.sleep(): Explicit waits are far more reliable because they wait only as long as needed for elements to load. - Test Locators: Verify your XPath/CSS selector works by searching for it in your browser’s dev tools (e.g., Chrome DevTools’ Elements tab search bar).
内容的提问来源于stack exchange,提问作者a4aravind

