简体   繁体   English

Selenium c# IWebElement 列表旧参考

[英]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.我有 div 元素列表,我在其中循环遍历在变量中保存旧数据的元素。

The div tag data look like this: div 标签数据如下所示:

<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.为了访问每个数据,我尝试了多种解决方案,包括 foreach、ElementAt 和使用 xpath 查找元素。 Here I need to get text and link for each element.在这里,我需要获取每个元素的文本和链接。

To get data using selenium c# following is the code要使用 selenium c# 获取数据,以下是代码

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通过 xpath 以及

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

Output for second iteration for every solution is Output 对于每个解决方案的第二次迭代是

link=Link1    text=Redirect 1

Expected output is预期 output 是

link=Link2    text=Redirect 2

Could you please help me on this.你能帮我解决这个问题吗? How to get latest data in itemDiv.如何获取 itemDiv 中的最新数据。 Currently it hold the reference of previous div element.目前它持有前一个 div 元素的引用。

You have to use .你必须使用. for immediate child of each div element.对于每个 div 元素的直接子元素。

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.问题是您使用的是 FindElement 而不是 FindElements,FindElement 方法将返回与条件匹配的第一个节点。

if you want to get all elements that match with the condition you need to use FindElements如果您想获取与您需要使用的条件匹配的所有元素 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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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