简体   繁体   中英

How to locate the element inside li tag using Selenium and C#

In my application, I want to assert a webelement name which is inside li tag. But I am unable to locate the same.

Below is the image of HTML code.I am unable to copy paste the code hence attaching the image.

在此处输入图像描述

The code which i tried is:

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.

your code may try to find the element before it exists, so my suggestion is use wait method. In Python it is something like:

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']"))));

But I don't know how to use it in C#.

Maybe you are losing some character inside the Xpath. This works for me:

'//*[@id="licredit-ResultDisplay"]/a/b'

Since you are not looking for a tag "li" but an element by "id"

I hope it can work for you:)

To get rid of OpenQA.Selenium.NoSuchElementException you have to induce WebDriverWait for the desired ElementIsVisible() and you can use either of the following Locator Strategies :

  • Using 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");
  • Using 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM