Selenium中如何使用IList升级可排序元素的操作代码?
Great question! Switching to IList<IWebElement> makes your code far more flexible—you’ll ditch hardcoded element locators, and it’ll adapt if the number of sortable items on the page changes. Here’s how to refactor your original drag-and-drop logic to use an IList:
Step 1: Grab all sortable items into an IList
Instead of locating individual elements, we’ll fetch all the sortable list items in one go. This gives us a collection we can work with dynamically.
Step 2: Replicate your original drag logic with the list
We’ll use the same Actions class, but reference items from our IList instead of hardcoded elements. Since IList uses 0-based indexing, sortableItems[0] is your original numberOne, and sortableItems[1] is numberTwo.
Here’s the full refactored code:
using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; // Navigate to the sortable page driver.Navigate().GoToUrl("http://demoqa.com/sortable"); // Wait for sortable items to load (optional but recommended for reliability) WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IList<IWebElement> sortableItems = wait.Until(d => d.FindElements(By.XPath("//*[@id='demo-tabpane-list']/div/div"))); // Initialize Actions for drag-and-drop Actions actions = new Actions(driver); // Drag the second item (index 1) to the position above the first item (index 0) actions.ClickAndHold(sortableItems[1]) .MoveToElement(sortableItems[0]) .MoveByOffset(0, 10) // Small vertical offset to ensure the drop triggers correctly .Release() .Perform();
Why this approach is better:
- No hardcoding: You don’t have to update XPath locators if new items are added or existing ones change.
- Scalability: Easily extend this to handle multiple drag operations (e.g., loop through the list to rearrange items in a specific order).
- Reliability: Adding a
WebDriverWaitensures we only interact with elements once they’re fully loaded, reducing flaky tests.
Bonus: Extending to custom sorting
If you wanted to rearrange items into a specific order (e.g., move item 3 to position 0), you’d just adjust the indices:
// Drag the fourth item (index 3) to the top position (index 0) actions.ClickAndHold(sortableItems[3]) .MoveToElement(sortableItems[0]) .MoveByOffset(0, -10) // Adjust offset direction if needed .Release() .Perform();
内容的提问来源于stack exchange,提问作者Gall Mladenova

