如何使用Selenium和C#来定位li标签中的元素。

问题描述 投票:0回答:2

在我的应用程序中,我想断言一个位于li标签内的webelement名称。但我无法找到相同的标签。

下面是HTML代码的图片,我无法复制粘贴代码,因此附上图片。

enter image description here

我尝试的代码是。

IWebElement result = driver.FindElement(By.XPath("//li[@id='licredit-ResultDisplay']/a/b"));
Assert.AreEqual(result.Text, "ESTIMATE RESULTS");
Console.WriteLine("Estimate Result validated successfully");

But I am getting no such element error.So kindly suggest any suitable way to locate the element to assert the name-ESTIMATE RESULTS.

c# selenium xpath css-selectors webdriverwait
2个回答
0
投票

你的代码可能会试图在元素存在之前找到它,所以我的建议是使用wait方法。在Python中,它是类似于.NET的方法,但我不知道如何使用。

driver = webdriver.Chrome(executable_path=r'D:PATHchromedriver.exe');
driver.get("https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver");
wait = new WebDriverWait(driver, 30 /*timeout in seconds*/);
wait.until(ExpectedConditions.element_to_be_clickable(By.xpath("//button[@id='btn1']"))));

但我不知道如何在C#中使用它。


0
投票

也许你在Xpath中丢失了一些字符。

'/*[@id="licredit-ResultDisplay"]ab' 。

因为你要找的不是 "li "这个标签,而是 "id "这个元素。

希望对你有用:)


0
投票

摆脱 OpenQA.Selenium.NoSuchElementException 你要诱导 WebDriverWait 为所欲为 ElementIsVisible() 您可以使用以下任何一种方式 定位策略:

  • 使用 CssSelector:

    IWebElement result = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("li#licredit-ResultDisplay>a>b")));
    Assert.AreEqual(result.Text, "ESTIMATE RESULTS");
    Console.WriteLine("Estimate Result validated successfully");
    
  • 使用 XPath:

    IWebElement result = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//li[@id='licredit-ResultDisplay']/a/b")));
    Assert.AreEqual(result.Text, "ESTIMATE RESULTS");
    Console.WriteLine("Estimate Result validated successfully");
    
© www.soinside.com 2019 - 2024. All rights reserved.