Sunday 23 August 2015

C# Webdriver - Fetch the names of checkboxes which are selected using 'Select' and 'Where' in a single LINQ statement.


Fetch the names of checkboxes which are selected using 'Select' and 'Where'.
using System;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Threading;
using System.Linq;


namespace TestConsoleApplication
{
    class Program
    {
        static void Main(string[] args)  
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl("http://www.tizag.com/htmlT/htmlcheckboxes.php");
            Thread.Sleep(3000);

            string xpath = "html/body/table[3]/tbody/tr[1]/td[2]/table/tbody/tr/td/div[6]/input";
            var list = driver.FindElements(By.XPath(xpath)).Where(p => p.Selected==true).Select(x => x.GetAttribute("value"));

            foreach(var text in list){
                Console.WriteLine(text);
            }
             
            Console.WriteLine("----------------");
            Console.ReadLine();

            driver.Close();
            driver.Quit();
            driver.Dispose();
        }
 
    }
}

Fetch the names of checkboxes which are selected without using 'Select' and 'Where'.
using System;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Threading;

namespace TestConsoleApplication
{
    class Program1
    {
        static void Main(string[] args)
        {

            IWebDriver driver = new FirefoxDriver();
            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl("http://www.tizag.com/htmlT/htmlcheckboxes.php");
            Thread.Sleep(2000);

            string xpath = "html/body/table[3]/tbody/tr[1]/td[2]/table/tbody/tr/td/div[6]/input";
            var webElements = driver.FindElements(By.XPath(xpath));

            foreach (var webElement in webElements)
            {
                if(webElement.Selected==true){
                    Console.WriteLine(webElement.GetAttribute("value"));
                }               
            }

            Console.WriteLine("---------------");
            Console.ReadLine();

            driver.Close();
            driver.Quit();
            driver.Dispose();
        }
    }
}


No comments:

Post a Comment