简体   繁体   中英

Selenium c# IWebElement list old reference

I have list of div elements where I am looping through elements which is holding the old data in the variable.

The div tag data look like this:

<div class="edu-lern-con">
   <h3>               
      <a href="#link1" target="_blank">Redirect 1</a>
   </h3>
</div>
<div class="edu-lern-con">
   <h3>               
      <a href="#link2" target="_blank">Redirect 2</a>
   </h3>
</div>

To access each data I have tried multiple solution which include foreach, ElementAt and finding element using xpath. Here I need to get text and link for each element.

To get data using selenium c# following is the code

foreach (var itemDiv in baseDiv)
{
    string link=itemDiv.FindElement(By.XPath("//h3/a")).GetAttribute("href");
    string text=itemDiv.FindElement(By.XPath("//h3/a")).Text;
}

also tried to do the same using

for (int j = 0; j < baseDivCount; j++)
{
    IWebElement itemDiv = driver.FindElements(By.ClassName("edu-lern-con")).ElementAt(j);
    string link=itemDiv.FindElement(By.XPath("//h3/a")).GetAttribute("href");
    string text=itemDiv.FindElement(By.XPath("//h3/a")).Text;
}

by xpath as well

IWebElement itemDiv = driver.FindElement(By.XPath("//div[@class='edu-lern-con'][" + (j + 1) + "]"));

Output for second iteration for every solution is

link=Link1    text=Redirect 1

Expected output is

link=Link2    text=Redirect 2

Could you please help me on this. How to get latest data in itemDiv. Currently it hold the reference of previous div element.

You have to use . for immediate child of each div element.

foreach (var itemDiv in baseDiv)
{
    string link=itemDiv.FindElement(By.XPath(".//h3/a")).GetAttribute("href");
    string text=itemDiv.FindElement(By.XPath(".//h3/a")).Text;
}

The problem is that you are using FindElement instead of FindElements, the method FindElement will return the First node that match with the condition.

if you want to get all elements that match with the condition you need to use FindElements

Code Example:

  var elements = Driver.FindElements(By.XPath("//h3//a[contains(@target,'_blank')]"));
    for (int i = 0; i < elements.Count; i++)
    {
        string text = elements[i].Text;
        string href = elements[i].GetAttribute("href");
    }

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