C# Selenium - dropdown menu/ combobox - c#

I have a problem selecting from a custom dropdown menu.. I have tried both by using the XPath, CssSelector and Id.
I have added a link to the code here:
Picture of the code
I think i have to access the div class="SelectBox" in order to access the id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype'
but i keep getting errors.
This is what I'm currently trying but without any luck:
IWebElement test = driver.FindElement(By.XPath("//div[#class='input']//div[#id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype']"));
Can someone give me a clue on how to get access to the items in the dropdown?
Thank you! :)

You need to use "SelectElement" instead of "IWebElement".
SelectElement mySelect = new SelectElement(yourDriver.FindElement(By.Id("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype")));
mySelect.SelectByText("510111 Normalbehandling");

Try This
var select = driver.FindElementById("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype");
var stringValues = select.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
((IJavaScriptExecutor)driver).ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, stringValues[0]);

Related

Verify the data from the last element of xpath with dynamic list c#

From the above image the new data that I add gets added to the last page but there can be similar name and I need to verify the data using the ID as shown. So I am trying to figure out the way to store text values from the id and when the new data is added it should verify the last newly added ID. Any ideas?
int i = 1;
bool found = false;
string ID;
try
{
IWebElement LastPage = Driver.driver.FindElement(By.XPath("html/body/div[4]/div/div/div[2]/table/tbody/tr[8]/td[1]"));
LastPage.Click();
for (i = 1; i <= 10; i++) ;
{
ID= Driver.driver.FindElement(By.XPath("html/body/div[4]/div/div/div[2]/table/tbody/tr[" + i + "]/td[1]")).Text;
if (??)
}
As #viet-pham said, using last is a good idea, you can also use a relative xpath like:
//table/tbody/tr[last()-1]/td
and you don't need to use [1] since you are using FindElement and not FindElements and is returning the first element found.
You don't need to use for loop to get the last item, just put last() to select the final tr element
In your case:
IWebElement lastElement = Driver.driver.FindElement(By.XPath("(html/body/div[4]/div/div/div[2]/table/tbody/tr)[last()]/td[1]"));
ID = lastElement.Text;
In additional: because the last row is the total, so you must change to the row before it => [last()-1]

How to get items from array element json c#

How do i get items from array element json c# ?
I want to get multiple artist names from my call, and put them in a listbox.
I can get the first artist like this etc.:
string url = #"http://api.musixmatch.com/ws/1.1/artist.search?apikey=key&q_artist=LMFAO&format=json";
string content = new WebClient().DownloadString(url);
dynamic artistData = JObject.Parse(content);
string artistName = artistData.message.body.artist_list[0].artist.artist_name;
But how can i get more of the names and put them in a listbox?
Here you can see how the json result looks like
Thanks in advance
You could try something like this
var artists = artistData.message.body.artist_list.Select(x => x.artist);
foreach (var artist in artists)
{
var artistName = artist.artist_name;
listBox.Items.Add(new ListBoxItem(artistName , artistName));
}
Hi you can use the below code snippet to get list of names
var artistNames = artistData.message.body.artist_list.Select(var=>var.artist.artist_name).ToList();
Then you could bind this list to your listbox either by using listbox.items.add function calls or by making use of ItemsSource property
Thanks for trying to help me, I really appreciate it. I figured out i could solve my problem like this:
var artistLength = artistData.message.body.artist_list.Count;
for (int i = 0; i < artistLength; i++)
{
var artistName = artistData.message.body.artist_list[i].artist.artist_name;
//printed in the console for testing
Console.WriteLine(artistName);
listBox1.Items.Add(artistName);
}

Getting ALL attributes from an IWebElement with Selenium WebDriver

I want to extract some information from the DOM with Selenium. I'm using the C# WebDriver.
Looking at the IWebElement interface you can easily extract a given attribute. However, I would like to extract all the attributes of an element without knowing their names in before hand.
There must be some simple way of doing this since there is a method for getting an attribute value if you know its name.
An example:
<button id="myButton" ng-click="blabla()" ng-show="showMyButton"
some-other-attribute="foo.bar" />
IWebElement element = driver.FindElement(By.Id("myButton"));
Dictionary<string, string> attributes = new Dictionary<string, string>();
// ???????
// Profit.
Hopefully I'm missing something obvious.
Thanks in advance!
The .attributes property in JavaScript will return an array of all the attributes a given element has and it's value.
So what you'll need to do is first get a driver that has the capability to run JavaScript:
IJavascriptExecutor javascriptDriver = (IJavaScriptExecutor)driver;
Now, execute it by:
Dictionary<string, object> attributes = javascriptDriver.ExecuteScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element) as Dictionary<string, object>;
The idea behind the JavaScript is to use the JavaScript attributes property within the element itself and then pull out the information we need - the name and value of the attribute. The attributes property, in reality, pulls a lot of information about each individual property but we want only two fields. So we get those two fields, put them into a dictionary and WebDriver will then parse it back to us. (It could probably be cleaned up a bit)
It's now a Dictionary and thus you can loop through however you like. The key of each pair will be the name of the attribute, and the value of each pair will be the value of the attribute.
Only tested this with a few elements dotted around the web (here, Google, and a few small web pages) and it seems to work well.
You can try this:
IWebElement element = driver.FindElement(By.Id("myButton"));
string elementHtml = element.GetAttribute("outerHTML");
This will give you the html of the element. From here, you can parse it, as Arran suggested
List<IWebElement> el = new List<IWebElement>(); el.AddRange(driver.FindElements(By.CssSelector("*")));
List<string> ag= new List<string>();
for (int b = 0; b < el.Count; b++)
{
ag.Add(el[b].GetAttribute("outerHTML"));
}
you can do a FindElement(By.tag("body")) to return a list of WebElements and then parse the results as you suggest.
You can try this:
Actions newTab = new Actions(web driver);
newTab.ContextClick(element).SendKeys(Keys.ArrowDown).SendKeys(Keys.ArrowDown).SendKeys(Keys.Return).Build().Perform();
I have created WebDriver Extension based on the first answer
public static List<string> GetElementAttributes(this RemoteWebDriver driver, IWebElement element)
{
IJavaScriptExecutor ex = driver;
var attributesAndValues = (Dictionary<string, object>)ex.ExecuteScript("var items = { }; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element);
var attributes = attributesAndValues.Keys.ToList();
return attributes;
}

How to get all options in a drop-down list by Selenium WebDriver using C#?

I'm new to both C# and Selenium WebDriver.
I know how to select/click on an option in a drop-down list, but I've a problem before that. Since the drop-down list is dynamically generated, I have to get all options/values from the list before running each case.
Is there anyone kindly tell me how to get all values/options from a drop-down list. I'm using IE and I didn't find any class which supports method to get values/options in Selenium.IE namespace for C#.
My example:
A list contains several time zones:
<TD>
<select name = "time_zone">
<option value "-09:00"><script>timezone.Alaska</script></option>
<option value "+00:00"><script>timezone.England</script></option>
<option value "+02:00"><script>timezone.Greece</script></option>
<option value "+05:30"><script>timezone.India</script></option>
</select>
<TD>
This is a drop-down list in an IE page and how to get the dynamically generated time zone list?
My code:
IWebElement elem = driver.FindElement(By.XPath("//select[#name='time_zone']"));
List<IWebElement> options = elem.FindElements(By.TagName("option"));
C# just pops an Error:
Cannot implicitly covert type 'OpenQA.Selenium.IWebElement' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?).
thanks.
You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:
IWebElement elem = driver.FindElement(By.XPath("//select[#name='time_zone']"));
SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;
You can then access each option as an IWebElement, such as:
IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");
Select select = new Select(driver.findElement(By.id("searchDropdownBox")));
select.getOptions();//will get all options as List<WebElement>
Make sure you reference the WebDriver.Support.dll assembly to gain access to the OpenQA.Selenium.Support.UI.SelectElement dropdown helper class. See this thread for additional details.
Edit: In this screenshot, you can see that I can get the options just fine. Is IE opening up when you create a new InternetExplorerDriver?
Here is code in Java to get all options in dropdown list.
WebElement sel = myD.findElement(By.name("dropdown_name"));
List<WebElement> lists = sel.findElements(By.tagName("option"));
for(WebElement element: lists)
{
String var2 = tdElement.getText();
System.out.println(var2);
}
Hope it may helpful to someone.
You can use selenium.Support to use the SelectElement class, this class have a property "Options" that is what you are looking for, I created an extension method to convert your web element to a select element
public static SelectElement AsDropDown(this IWebElement webElement)
{
return new SelectElement(webElement);
}
then you could use it like this
var elem = driver.FindElement(By.XPath("//select[#name='time_zone']"));
var options = elem.AsDropDown().Options
Use IList<IWebElement> instead of List<IWebElement>.
For instance:
IList<IWebElement> options = elem.FindElements(By.TagName("option"));
foreach (IWebElement option in options)
{
Console.WriteLine(option.Text);
}
To get all the dropdown values you can use List.
List<string> lstDropDownValues = new List<string>();
int iValuescount = driver.FindElement(By.Xpath("\html\....\select\option"))
for(int ivalue = 1;ivalue<=iValuescount;ivalue++)
{
string strValue = driver.FindElement(By.Xpath("\html\....\select\option["+ ivalue +"]"));
lstDropDownValues.Add(strValue);
}
WebElement drop_down =driver.findElement(By.id("Category"));
Select se = new Select(drop_down);
for(int i=0 ;i<se.getOptions().size(); i++)
System.out.println(se.getOptions().get(i).getAttribute("value"));
WebElement element = driver.findElement(By.id("inst_state"));
Select s = new Select(element);
List <WebElement> elementcount = s.getOptions();
System.out.println(elementcount.size());
for(int i=0 ;i<elementcount.size();i++)
{
String value = elementcount.get(i).getText();
System.out.println(value);
}
To get all options in a drop-down list by Selenium WebDriver C#:
SelectElement TimeZoneSelect = new SelectElement(driver.FindElement(By.Name("time_zone")));
IList<IWebElement> ElementCount = TimeZoneSelect.Options;
int ItemSize = ElementCount.Count;
for (int i = 0; i < ItemSize; i++)
{
String ItemValue = ElementCount.ElementAt(i).Text;
Console.WriteLine(ItemValue);
}
It seems to be a cast exception. Can you try converting your result to a list
i.e. elem.findElements(xx).toList ?
You need to pass the desired select webelement here and you can use getOptions() that helps you to get all the options of the drop-down.
Now you can get all the elements one-by-one using loop and you can print it on the console.
Select s = new Select(driver.findElement(By.xpath("<xpath>")));
// getting the list of options in the dropdown with getOptions()
List <WebElement> op = s.getOptions();
int size = op.size();
for(int i =0; i<size ; i++)
{
String options = op.get(i).getText();
System.out.println(options);
}

Retrieve Value of DropDownList by Index ID

I am trying to retrieve the value of a dropdown list by specifying its indexid but I cant seem to find a way to accomplish this. I dont want it to be the selected value either, basically I need to go through the list, and then add it to an array. I can find all kinds of ways to get it based on the value but not by the index id anyone know how to do this? Im using c#.
string valueAtIndex = myComboBox.Items[SomeIndexValue].Value;
Have you tried lstWhatever.SelectedIndex?
Since the object supports IEnumerable, you can use foreach to loop through, if that is your intention.
Is this what you are looking for?
List<String> theList = new List<string>();
foreach (var item in comboBox1.Items)
{
theList.Add(item.ToString());
}
Where comboBox1 is your dropdown list and i assumed you are talking about a windows forms project.
Or, if you want to us Index Id:
List<string> theList = new List<string>();
for (int i = 0; i < comboBox1.Items.Count; i++)
{
theList.Add(comboBox1.Items[i].ToString());
}
String valueAtIndex = myComboBox.Items[myComboBox.SelectedIndex].ToString();

Categories