简体   繁体   English

Selenium C#:如何在另一个类中获取一个类的属性/属性?

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

Here is a body of an HTML file这是一个 HTML 文件的正文

<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".但是现在,我想要的是从“img”类和“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.由于类imgdate都在同一个父类pic ,您可以使用公共 xpath 获取列表中的两个值,然后遍历该列表以获取所需的值。
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();

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

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