简体   繁体   中英

Selenium C#: How to get the properties/attributes of a class inside another class?

Here is a body of an HTML file

<div class ="pic">
  <a class = "img" href = "abcxyz.com">
  </a>
  <a class = "date" href = "asdfg.com">
     <span> Feb 02 </span>
  </a>
</div>

Here is my code doing the job when I want to get the information like, get the image link

List<IWebElement> imgElements = driver.FindElements(By.ClassName("img")).ToList();
foreach (IWebElement imgElement in imgElements)
{
    img_URL = imgElement.GetAttribute("href").;
    Console.WriteLine(img_URL);
}

But now, what I want is, to get both links and info from class "img" and class "date". Please help me to optimize that. Thanks in advance.

As both the classes img and date are in the same parent class pic , you can fetch both the values in a list using a common xpath and then iterate over that list to fetch the values that you want.
You can do it like:

List<IWebElement> imgElements = driver.FindElements(By.Xpath("//div[@class='pic']//a")).ToList();
foreach (IWebElement imgElement in imgElements)
{
    img_URL = imgElement.GetAttribute("href");
    Console.WriteLine(imgElement.Text);
    Console.WriteLine(img_URL);
}

You can create a method for resolving specific tags, like this (I am using it for resolving labels):

public static IWebElement ResolveLabelFromElement(this IWebElement labelValuePairElement)
        {
            By by = By.TagName("label");
            var label = labelValuePairElement.FindElement(by);

            return label;
        }

And use like this:

var labelElement = element.ResolveLabelFromElement();

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