Get Checkbox label text Selenium C# - c#

I'm trying to get the text value of checkbox label. Here is an HTML code
<div id="content" class="large-12 columns">
<div class="example">
<h3>Checkboxes</h3>
<form id='checkboxes'>
<input type="checkbox"> checkbox 1</br>
<input type="checkbox" checked> checkbox 2
</form>
</div>
So What I have tried so far
Driver.FindElement(By.XPath("//input[#type='checkbox']")).Text;
Driver.FindElement(By.XPath("//input[#type='checkbox']")).GetAttribute("value");
Driver.FindElement(By.XPath("//input[#type='checkbox']")).GetAttribute("name");
Driver.FindElement(By.XPath("//input[#type='checkbox']")).GetAttribute("innerText");
Driver.FindElement(By.XPath("//input[#type='checkbox']")).GetAttribute("innerHTML");
Here is a screenshot
All this attempts return "".
Any ideas how to get it or Javascript is my only option ?

The xpath for a text following an input tag is //input[1]/following-sibling::text()[1] but there are serious limitations for Selenium to run expressions like this. It only can handle tag elements. Try to get the parent and retrieve texts from there.
string[] texts = Driver.FindElement(By.XPath("//form[#id='checkboxes']"))
.GetAttribute("innerText")
.Split("\r\n".ToCharArray()
);
Then texts[0] returns:
checkbox 1

Add an class or id attribute to the checkboxes and then try to find the element by css selector like: Driver.FindElement(By.CssSelector(""))

You can try following to get the required text from the two checkboxes:
Driver.FindElement(By.XPath("//form[#id='checkboxes']/input[#type='checkbox'][1]")).Text
Driver.FindElement(By.XPath("//form[#id='checkboxes']/input[#type='checkbox'][2]")).Text
Let me know, if above code does not work for you.

You can also use CSS Selector to get the checkbox label:
Element CheckBox = Driver.FindElement(By.CssSelector("input[type='checkbox']"));
string firstChkBoxTxt = CheckBox.FirstOrDefault().GetAttribute("innerText");
string secondChkBoxTxt = CheckBox.LastOrDefault().GetAttribute("innerText");

Related

How to get xpath of different html values with the same properties

I'm working on Selenium and trying to get the values inside tags. The site that I'm working on is https://www.qnbfinansbank.enpara.com/doviz-kur-bilgileri/doviz-altin-kurlari.aspx. But the properties of the objects are the same. Therefore, the xpath scripts are the same. The values that I'm trying to get are like 5,615505 TL, 4,827450 TL, 187,389825 TL from
<div class="dlCont">
<span>5,615505 TL </span>
</div>
<div class="dlCont">
<span>4,827450 TL </span>
</div>
<div class="dlCont">
<span>187,389825 TL </span>
</div>
and so on. Is there any way to get the xpath of these values?
You can store all the values in a List. Then one by one you can retrieve it.
Something like :
IList<IWebElement> allValues= driver.FindElements(By.CssSelector("div.dlCont span"));
foreach (IWebElement values in allValues)
{
Console.WriteLine(values.Text);
}
Hope this will help.
You can use like this,
//span[contains(text(),'5,615505 TL')]
You can manually write the xpath for the below DOM Structure
<div class="dlCont">
<span>5,615505 TL </span>
</div>
Manually written xpath for above DOM structure is "//div[#class='dlCont']/span".
if the page is having many elements with same DOM struture then written Xpath will match with all the nodes.
There are 8 nodes are matched with XPATH="//div[#class='dlCont']/span" in the below URL https://www.qnbfinansbank.enpara.com/doviz-kur-bilgileri/doviz-altin-kurlari.aspx
if you want to fetch particular webelements then you need to specify the index value as "(//div[#class='dlCont']/span)[2]".
you need to add open bracket in the starting of the manually written xpath and close bracket in the ending of the Xpath.after that you need to mention the index value
1.//div[#class='dlCont']/span
2.(//div[#class='dlCont']/span
3.(//div[#class='dlCont']/span)
4.(//div[#class='dlCont']/span)[1]
Hope it will be helpful

How to sendkeys to a <p> tag through C# and Selenium

i want to sendkeys "description" within a textarea. I have tried all the possible ways but does not work.
HTML of the element :
<div class="ta-scroll-window ng-scope ta-text ta-editor form-control" ng-hide="showHtml">
<div class="popover fade bottom" style="max-width: none; width: 305px;">
<div class="arrow"></div>
<div class="popover-content"></div>
</div>
<div class="ta-resizer-handle-overlay">
<div class="ta-resizer-handle-background"></div>
<div class="ta-resizer-handle-corner ta-resizer-handle-corner-tl"></div>
<div class="ta-resizer-handle-corner ta-resizer-handle-corner-tr"></div>
<div class="ta-resizer-handle-corner ta-resizer-handle-corner-bl"></div>
<div class="ta-resizer-handle-corner ta-resizer-handle-corner-br"></div>
<div class="ta-resizer-handle-info"></div>
</div>
<div id="taTextElement737852736512107" contenteditable="true" ta-bind="ta-bind" ng-model="html" ta-keep-styles="true" class="ng-pristine ng-valid ta-bind ng-empty ng-touched" an-form-object-name="Açıklama" name="Açıklama">
<p>
<br>
</p>
</div>
</div>
Code trial :
Dim action2 = New Actions(driver)
Dim cekbul2 = driver.FindElement(By.XPath("//*#id=""taHtmlElement737852736512107""]"))
cekbul2.SendKeys("Açıklama")
Console.Write("textarea send description")
or
Dim cekbul2 = driver.FindElement(By.XPath("//textarea[#class='ng-pristine ng-untouched ng-valid ng-scope ta-bind ta-html ta-editor form-control ng-empty ng-hide' and #id='taHtmlElement737852736512107']"))
The error is :
"no such element: Unable to locate element does not work" give error
Your html does not have a text area input field inside it.
When you use an xPath that says
'//textarea' this means that you are looking for an element that has tags of <textarea> </textarea>
It looks like your html is actually div's that are styled up to look like text areas.
That is why your second attempt will never work - because you are looking for a textarea where none exists.
Typically, in the situation where a div is styled up to work like a text area or textbox, you will find that the div has a backing input behind it.
These must be located between the
<form> and </form> tags in the html - otherwise the server would never be able to receive the data. (Html 5 provides new ways of working with this - but that is another story)
Can you examine your full html, and see if you can find the actual text area objects or the input type objects that end up containing the text content.
Type some dummy text, and use an html inspector tool within chrome or firefox to look for your dummy text.
If however, the post is completed by javascript - you may find that the javascript does not use inputs or text areas for containing the text and instead posts it external to any form elements. This is common with richtext emulators such as forum post pages.
If that is the case- you may need to experiment and find the appropriate html element that you need to send keys to in order for the content to work.
Also - could you try
Dim cekbul2 = driver.FindElement(By.XPath("//div[#id='taHtmlElement737852736512107']"))
I couldnt help but notice it had an xPath syntax error - you had no starting [ square bracket ] - also, in programming it is sometimes considered lazy a bad practice to wildcard / work with dynamics. I recommend always using the tag type for your xpaths, as opposed to '//*'
Worse case scenario, I would say that you could probably get around this by using Javascript execution. Eg: Directly setting the text, instead of 'sending the key strokes'.
However, this does not emulate human behavior - but it may be a necessary evil depending on your situation.
To send text to the <p> tag you have to use the ExecuteScript() method from IJavaScriptExecutor Interface and you can use the following code block :
((IJavaScriptExecutor)driver).ExecuteScript("document.getElementsByTagName("p")[0].innerHTML="Hasan Sarıkaya";");
I want to highlight some points here
Most probably your locator which you are using is not correct.
There are three way which I know to enter text using selenium
1)Use driver.findElement(yourLoator).sendKeys("Stringvalue");
2)You can use action class to send keys
3)You can use javascript executor to change innerHtml code
Personally ill not prefer the third solution, because we are testers I believe changing dom attribute is a good practice
Hope this will give you some help. please Let me know in case any query.

How to get field value - selenium c#

Im trying to get field value (having link inside) for future use, so i want to place it under parameter.
the problem is the his class name used if 7 more fields so he isnt unique.
is there a way to get this field value using the label value above this field (called "Get direct link")?
<div class="form-group">
<label>Get direct link:</label>
<input class="form-control" type="text" style="cursor: auto;
value="http://ds2.dev.polebeary.com/api/download/1521723231257836/qa_yaakov_tevel.dmg" readonly="">
</div>"
need the link (who can be change of course..)
What you need here is XPath. Find this element by using following XPath expression.
//div[#class="form-group"][label[text()="Get direct link:"]]/input
Means: Select input field which is in a div. That div has an attribute class = "form-group" and at least have a child with name label, and that label has text "Get direct link:" in it.
For C# syntax
if you are using IWebDriver:
var element = driver.FindElement(By.XPath("//div[#class="form-group"][label[text()="Get direct link:"]]/input"));
if you are using WebDriverWait:
var element = waitDriver.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[#class="form-group"][label[text()="Get direct link:"]]/input")));

How to change a HTML Textbox with C#

I was wondering if anybody knew how to change the contents of a HTML TextBox with C# I have tried to use body.SetAttribute("value", string) but I did not get anywhere. An example of what I am trying to do is <textarea rows="2" cols="20" id="body" class="messages-reply-box text-box text new-message-body">String I need changed</textarea> Here is what I got so far:
HtmlDocument doc = webBrowser1.Document;
HtmlElement bod = doc.GetElementById("body");
bod.SetAttribute("value", "text");
If you want change the Text of a Element inside your html page you should use InnerText property. This should work
webBrowser1.Document.GetElementById("body").InnerText ="text";

how to get the value from input control of html

I have a table which is generated by a 3rd party control. This table has only one row and one column. Within this column is html text as follows :
<p>
this is a test</p>
<p>
<input name="amount" type="text" value="this is for amount" /></p>
<p>
this is a test</p>
<p>
<input name="test" type="text" value="this is for test" /></p>
<p>
this is a test</p>
the problem is how to get the value saved inside the html input control ?
I tried the following code but it fails:
t.Rows[0].Cells[0].FindControl("amount");
thanks in advance...
You can use the below snippet to retrieve the required values inside the javascript function:
function getValue()
{
//First method
var val= document.getElementsByName("amount");
alert("Val by Element Name:-" +val(0).value);
//Second method
val= document.getElementById("amount");
alert("Val by element Id:-" +val.value);
//third method
val= document.getElementsByTagName("input");
alert("Val by Tag:-" +val(0).value);
alert("Val by Tag:-" +val(1).value);
}
Assumption: You're aware of the names of the input controls inside the table obtained by the 3rd party tool.
Do you mean when the form is posted back? In that case, just use
Request["amount"]
to get the value.
Since it is a 3rd party control, it should give you access to the values of the controls throught the properties of the controls. Check the properties and documentation.
Use a HiddenControl and jQuery.
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(documet).ready(function(){
var inputVals = '';
$('#yourThirdPartyTableID').find('input[type=text]').each(function() {
inputVals = inputVals + $(this).val() + ', ';
});
$('#<%= YourHiddenControlID.ClientID %>').val(inputVals);
});
</script>
The above code will insert values of all text inputs from your third party table into the hidden control separated by a comma. You can change the comma into anything else to make it easier to split on server side code.
If you're looking for the value of the input with "name" of "amount", do the following:
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(documet).ready(function(){
$('#<%= YourHiddenControlID.ClientID %>').val($('#yourTableID').find('[name="amount"]').val());
});
</script>
There is no straight forward method to retrieve the value of an input control unless you say runat="server".
My suggestion is to use the runat="server" tag and try getting the value using VALUE property.
Otherwise you can use Page.FindControl('') and see whether the control is returning other than null...then i feels that will work.
if you are using ajax or master-content page then the controls id will be not the one you given....so make sure you are giving the correct id itself (using view source of the page)

Categories

Resources