You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium(C#)中如何查找相似路径列表文本并验证购物车添加项

Hey there! Let's tackle your Selenium (C#) challenges step by step— I’ve dealt with similar scenarios when testing e-commerce platforms, so I’ve got some practical tips for you.

1. 查找列表中具有相似路径的文本

The main issue here is likely using FindElement instead of FindElements— the former only grabs the first matching element, which explains why you’re getting text mismatches. Here’s how to fix it:

  • Use FindElements to get all matching elements: This method returns a collection of all elements that match your selector, letting you iterate through them.
  • Add explicit waits: If your list loads dynamically, make sure to wait for all elements to be visible before trying to access them— this avoids missing elements that haven’t loaded yet.

Example Code (C#)

// Set up explicit wait (adjust timeout as needed)
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

// Wait for all elements in the list to be visible
var itemElements = wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
    By.XPath("//div[contains(@class, 'product-list-item')]/span[@class='item-text']")
));

// Iterate through each element to check text
foreach (var element in itemElements)
{
    string itemText = element.Text.Trim();
    // Check if this is the text you're looking for
    if (itemText.Equals("Your Target Text", StringComparison.OrdinalIgnoreCase))
    {
        // Do something with the matching element (e.g., click it)
        element.Click();
        break;
    }
}

Pro Tip for Dynamic Lists

If elements load as you scroll, you’ll need to scroll the page incrementally and keep checking for new elements until you find your target or reach the end of the list.


2. 高效验证商品是否成功添加至购物车

Traversing 30 cart items one by one is slow because each element.Text call involves a round-trip to the browser. Here are faster alternatives:

Option 1: Check the Cart Count Badge

Most e-commerce sites show a count of items in the cart (e.g., a number next to the cart icon). Validate this count before and after adding the item:

// Get initial cart count
int initialCount = int.Parse(driver.FindElement(By.CssSelector(".cart-badge")).Text);

// Add your product to cart...

// Get updated cart count
int updatedCount = int.Parse(driver.FindElement(By.CssSelector(".cart-badge")).Text);

// Verify count increased by 1
Assert.AreEqual(initialCount + 1, updatedCount);

Option 2: Look for the Item’s Unique Identifier

Instead of matching text (which can be duplicate), use a unique attribute like SKU, product ID, or data attribute. This is faster and more reliable:

// After adding the item, go to the cart page
driver.Navigate().GoToUrl("your-cart-page-url");

// Wait for cart items to load
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".cart-items")));

// Check if the item with target SKU exists
bool isItemInCart = driver.FindElements(By.CssSelector($"tr.cart-item[data-sku='TARGET-SKU']")).Any();

Assert.IsTrue(isItemInCart, "Item not found in cart");

Option 3: Use JavaScript for Bulk Data Retrieval

JavaScript can fetch all cart item data in one go, reducing browser round-trips. This is way faster for large carts:

// Execute JS to get all cart item SKUs
var cartSkus = (IEnumerable<string>)driver.ExecuteScript(@"
    return Array.from(document.querySelectorAll('tr.cart-item')).map(item => item.getAttribute('data-sku'));
");

// Check if target SKU is in the list
Assert.IsTrue(cartSkus.Contains("TARGET-SKU"), "Item not present in cart");

Key Optimization: Avoid Thread.Sleep

Always use explicit waits (WebDriverWait) instead of hard-coded sleeps— this ensures you only wait as long as needed, speeding up your tests.


内容的提问来源于stack exchange,提问作者AnnaStarling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:37:41