Home > Software engineering >  Return results from FindElements as an array of links
Return results from FindElements as an array of links

Time:12-19

I have a class something like this:

someclass.cs

namespace XXX
{
    internal class yyy
    {
        public string getlink(string urlz)
        {
            var options = new ChromeOptions();
            using var driver = new ChromeDriver(options);
            driver.GoToUrl(urlz);
            var getlinks = driver.FindElements(By.XPath(".//xxxx/a"));
            foreach (var link in getlinks )
            {
                string resultlink = link.GetAttribute("href");
            }
            //question here
            return as array resultlink
        }
    }
}

My question, based on the code above, is how I can return all resultlink as array so I can use it this function in a form?

For example

form1

yyy listlink = new yyy();
var listalllink = listlink.getlink("domaindotcom");
foreach (var singlelink in listalllink )
{
    //do what ever I want
}

CodePudding user response:

just use List class to hold link collection

var getlinks = driver.FindElements(By.XPath(".//xxxx/a"));
List<string> array = new List<string>();
foreach (var link in getlinks )
    {
      string resultlink = link.GetAttribute("href");
      array.Add(resultLink);
    }
//question here
return array.toArray();

or use Linq(prefer):

getlinks.Select(link -> link.GetAttribute("href")).ToArray();

CodePudding user response:

Your GetLink method should be:

public static IEnumerable<string> GetLink(string urlz)
{
    var options = new ChromeOptions();
    using var driver = new ChromeDriver(options);

    var elements = driver.FindElements(By.XPath(urlz));

    return elements.Select(element => element.GetAttribute("href")).ToArray();
}
  • Related