Selenium Webdriver: Cant find element by classname - c#

I am currently struggling with Selenium to select an element by its class name.
The Website I'm using is:
http://demo.guru99.com/test/login.html
<div class="col-xs-12 col-sm-6">
<form action="success.html" method="post" id="login_form" class="box">
<h3 class="page-subheading">Already registered?</h3>
<div class="form_content clearfix">
<div class="form-group">
<label for="email">Email address</label>
<input class="is_required validate account_input form-control" data-validate="isEmail" type="text" id="email" name="email" value="">
</div>
<div class="form-group">
<label for="passwd">Password</label>
<span><input class="is_required validate account_input form-control" type="password" data-validate="isPasswd" id="passwd" name="passwd" value=""></span>
</div>
<p class="lost_password form-group">Forgot your password?</p>
<p class="submit">
<input type="hidden" class="hidden" name="back" value="my-account"> <button type="submit" id="SubmitLogin" name="SubmitLogin" class="button btn btn-default button-medium">
<span>
<i class="icon-lock left"></i>
Sign in
</span>
</button>
</p>
</div>
</form>
</div>
I figured out how to select the element by id but whenever I try to select it by classname I get an element not found exception. I don't really understand how this works as I tried multiple websites without success. In this example the element has multiple classes but on some websites this method even fails when there is only one class. On this website selecting it by only one class works but I have read that this isn't a good method as you could be selecting multiple elements by mistake.
IWebElement search = driver.FindElement(By.ClassName("account_input"));
Here is my code:
driver = new ChromeDriver();
driver.Url = "http://demo.guru99.com/test/login.html";
driver.Navigate();
IWebElement search = driver.FindElement(By.ClassName("is_required.validate.account_input.form-control"));
search.SendKeys("test");
In this example selecting element by Id using the By.Id("first_name") method doesn't work either:
<span>
<label class="first_name_label form_label_text"></label>
<div class="clear"></div>
<div class="form-item icon">
<input value="" data-error="An error has occured." id="first_name" type="text" name="first_name" class="form_item is_required" placeholder="First Name">
<i style="color:rgba(70,75,106,0.5)" class="vs icon-user"></i> </div>
<div class="form-item icon">
<input value="" data-error="An error has occured." id="last_name" type="text" name="last_name" class="form_item is_required" placeholder="Last Name">
<i style="color:rgba(70,75,106,0.5)" class="vs icon-user"></i> </div>
<div class="clear"></div>
</span>
What am I doing wrong? Help would be greatly appreciated

You can use the class name to find the element as well, But what is the problem is that same class can be used to define multiple element in the program , So when you find element by class it will not assure you that it will find the element which you are hoping for.
Selenium will find element of the first in the result.
Better to with xpath like tag along with the class.
Here is the code
xpath = " //input[#name='passwd'] ";
# -> can be used to get any parameter inside the tag and use it as per your requirement.
This will help you.
Contact for more information.

Corrected Code: Xpath of your class name was incorrect.
driver = new ChromeDriver();
driver.Url = "http://demo.guru99.com/test/login.html";
driver.Navigate();
IWebElement search = driver.FindElement(By.ClassName("is_required validate account_input form-control"));
search.SendKeys("test");
Another way to access email field is:
IWebElement search = driver.FindElement(By.Xpath("//*[#id='email']"));
Hope this helps.

If you will observe the class name of the element, it is the compound class name(having space in between). And compound class names are not permitted in selenium. In this case, you can use another locator like CSS(with class name) or XPath.
Check the following code snippet:
WebDriverManager.chromedriver().version("2.40").setup();
WebDriver driver= new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://demo.guru99.com/test/login.html");
WebElementuserName=driver.findElement(By.cssSelector(".is_required.validate.account_input.form-control"));
userName.sendKeys("Username");
WebElement password = driver.findElement(By.xpath("(//[#class='is_requiredvalidateaccount_input form-control'])[2]"));
password.sendKeys("Password");

Related

How to validate the title of text box in selenium c#

In my application,one of the page has more dropdown box and text box.I am tring to validate the title of each text box and dropdown box but i am unable to construct proper xpath for doing assertion.
Below is the HTML code of that text box and dropdown box.
The title of the text box and dropdown is as below:
Please Select Credit Type:
How Much Do You Need?
Loan Term
Employment Type
<div class="row">
<div class="col-md-6">
<label class="control-label" for="creditType">Please Select Credit Type:</label>
<select class="form-control" id="CreditType" name="creditType" required="" onclick="hideError(this)" onchange="onProductSelection()" onfocus="hideError(this)">
<option value="1" id="inputDivMaster-1" selected="">Personal Loan</option>
<option value="2" id="inputDivMaster-2">Credit Card</option>
</select>
</div>
<div class="col-md-6">
<label class="control-label" for="loanAmount">How Much Do You Need?</label>
<input type="text" class="form-control allownumericwithoutdecimal" id="loanAmountInput" name="loanAmount" placeholder="R500 - R249 999" pattern="\d*" maxlength="6" onclick="hideErrorById('loanAmount')" value="249999" onfocus="hideErrorById('loanAmount')">
<span class="dl-error-msg" id="loanAmountError" style="display: none;"> </span>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="control-label" for="loanTerm">Loan Term (Months)</label>
<input type="text" class="form-control allownumericwithoutdecimal" id="loanTermInput" name="loanTerm" placeholder="1 - 84 months" pattern="\d*" maxlength="2" onclick="hideErrorById('loanTerm')" value="80" onfocus="hideErrorById('loanTerm')">
<span class="dl-error-msg" id="loanTermError" style="display: none;"> </span>
</div>
<div class="col-md-6">
<label class="control-label" for="employmentStatus">Employment Type</label>
<select class="form-control" id="EmploymentStatusInput" name="employmentStatus" required="" onclick="hideErrorById('EmploymentStatus')" onfocus="hideErrorById('EmploymentStatus')"><option value="1">Permanent</option><option value="2">Temp/Seasonal/Casual worker</option><option value="3">Unemployed</option><option value="4">Pensioner</option><option value="5">Contract Worker</option><option value="6">Self Employed</option></select>
<span class="dl-error-msg" id="EmploymentStatusError" style="display: none;"> </span>
</div>
</div>
I am unable to construct xpath for locating the proper webelement to assert the title since the class name is same for all text boxes.Only the 'for' attribute gets changed.
What is the right way to locate the element.Kindly suggest suitable xpath.
String actual_title = driver.FindElement(By.XPath("_____?______")).Text;
String expected_title = "Please Select Credit Type:";
Assert.AreEqual(actual_title, expected_title);
Console.WriteLine("Text Box Title validated successfully");
You can use any attribute from the webelement as part of the xpath. In this case, you can use "for" attribute like this,
By.XPath("//label[#for='creditType']")

Unable to click on Sign-in button

<div class="form-group dl-padding-10">
<select class="form-control form-control-solid" name="SelectedRoleID" id="SelectedRoleID" onchange="removeBorderColor()" required="">
</select>
<div class="dl-align-left" id="show_text" style="color:red">
</div>
</div>
<div class="circle1-mask form-group" id="FingerprintContent" style="height:140px;z-index:2; background-image: none;">
<img src="Assets/img/fingerprint4.gif" id="fingerprint-img" data-status="active" style="height:140px; width:100px;" onclick="DeviceScript.scanFingerPrint(event)">
</div>
<div class="form-group dl-padding-10">
<button type="submit" id="register-btn" class="btn btn-block dl-button-primary dl-no-margin">Sign In (For Testing Purpose Only)</button>
</div>
</div>
</div>
</form> </div>
</div>
<button type="submit" id="register-btn" class="btn btn-block dl-button-primary dl-no-margin">Sign In (For Testing Purpose Only)</button>
U can find the HTML code with most information above.
HTML for the button is present in the last line of the above code.
My coding:[code][2]
Error which i get :
OpenQA.Selenium.ElementClickInterceptedException : element click intercepted: Element <button type="submit" id="register-btn" class="btn btn-block dl-button-primary dl-no-margin">...</button> is not clickable at point (758, 646). Other element would receive the click: <div class="footer navbar-fixed-bottom">...</div>
Kindly help me out on this.
To click on registered button Induce WebDriverWait and wait for ElementToBeClickable
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("register-btn"))).Click();
If you still have the same issue then you need to induce Javascript Executor to click.
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].click();", driver.FindElement(By.Id("register-btn")));

ASP.NET Core Model Binding: Using Dropdown List as Label

I am making an ASP.NET Core Mvc web app and am working on a search form. In the form, a user can be looked up by first name, last name, zip, and either ID, email, or phone. Whether a user is inputting ID, email, or phone is determined by a drop down list. I want to bind this to the User model I have but am not sure how to do it dynamically with the dropdown list. I am able to bind first name, last name, and zip just fine since they are not dynamic fields. Code for what I have so far for the form is below:
<form asp-action="Search">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label for="sel1">Search By:</label>
#* The dropdown menu to choose input type *#
<select class="form-control" id="sel1">
<option>ID</option>
<option>Email</option>
<option>Phone</option>
</select>
</div>
#* Where users would input information for the dropdown field *#
<div class="form-group">
<label for="id">Value:</label>
<input type="text" class="form-control clearable" id="id" Placeholder="0123456789">
</div>
<div class="form-group">
<label asp-for="FirstName">First Name:</label>
<input asp-for="FirstName" type="text" class="form-control clearable" id="firstName" Placeholder="Jane">
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName">Last Name:</label>
<input asp-for="LastName" type="text" class="form-control clearable" id="lastName" Placeholder="Doe">
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Zip">Zip Code:</label>
<input asp-for="Zip" type="text" class="form-control clearable" id="zipCode" Placeholder="55555">
<span asp-validation-for="Zip" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-default" id="search" />
</div>
</form>
Then the code where the model is bound on the Search function:
public async Task<IActionResult> Search([Bind("FirstName, LastName, Zip")] Consumer consumer)
{
// Code....
}
Is there a way to dynamically bind the input for the text input with id="id" based on the dropdown menu selection? Thanks in advance.
There's two options:
Render all the fields to the page (first, last, zip, etc.), and then use JavaScript to hide/show those fields based on the selection in the drop down list. For example, if you select "First Name", then show the FirstName input and hide the others. The user then enters their keywords in that input, and when they post, it will bind to FirstName naturally.
Post the value of the drop down and a generic text input. In your action, you can then simply switch on the value of the drop down and query the right property:
IQueryable<Foo> query = db.Foos;
switch (model.MyDropDownSelection)
{
case "FirstName":
query = query.Where(x => x.FirstName.Contains(keyword));
break;
// etc.
}

Select input fields from html form in selenium

I want to select input fields from the following form in selenium. I have tried many methods but found no help and my test always fails.
Here is the html form:
`<form class="login" action="/Index/trylogin/?ru=L015RmlueWE=" novalidate>
<fieldset>
<label>
<input type="text" maxlength="14" tabindex="1" value="" placeholder="Pseudonym">
</label>
<label>
<input type="password" maxlength="20" tabindex="2" data-ch="8H7vtP9f9tns3TGMJ6F995kTyLSmwFsdDlIyBLhBBsrrW1ZHIZiec4cPqF7C5sp5" data-ch2="1782447a8c3759d4407ed522b831806e8cfde5dc" placeholder="Kennwort">
</label>
<input type="submit" value="Anmelden" class="button button-style1">
<div class="login-options">
<label>
<input type="checkbox" value="1" name="stayon">Automatisch anmelden (auf diesem Gerät)
</label>
</div>
</fieldset>
</form>`
Her is my test method
[TestMethod]
public void Login_FinYa_System()
{
IWebElement login = _driver.FindElement(By.XPath("//form[1]"));
IWebElement pass = _driver.FindElement(By.XPath("//form[2]"));
login.Click();
login.SendKeys("helo");
pass.Click();
pass.SendKeys("123");
pass.SendKeys(Keys.Enter);
Assert.AreEqual("hello", "hello");
}
You are using incorrect xpath for login and password field.
Try this.
WebElement login = driver.findElement(By.xpath("//input[#type='text']"));
WebElement password = driver.findElement(By.xpath("//input[#type='password']"));
login.click();
login.sendKeys("hello");
pass.click();
pass.sendKeys("123");
pass.sendKeys(Keys.Enter);
Assert.assertEquals("hello", "hello");

Clicking class button on website

I have the following code for a webpage;
<div class="toolbox">
<div class="toolboxNest" align="left">
<div class="clear"> </div>
<div class="gap"> </div>
<label for="j_username">
<input id="j_username" type="text" name="j_username">
<div class="clear"> </div>
<div class="gap"> </div>
<label for="j_password">
<input id="j_password" type="password" name="j_password">
</div>
<div class="clear"></div>
<div class="gap"></div>
<div align="center">
<input class="formButtonGreen" type="submit" value="Login">
</div>
<div class="clear"></div>
<div class="gap"></div>
<div class="infoText">
I am able to click and enter text for the username and password, but I cant work out how to press the submit button, if it were just an element then that would be fine, but it's in a class and I'm unsure how to do it.
This is my code...
var x = webBrowser1.Document.All.GetElementsByName("j_username");
x[0].InnerText = "xxxxx";
var y = webBrowser1.Document.All.GetElementsByName("j_password");
y[0].InnerText = "xxxxxxxx";
//This part is not working....
var s = webBrowser1.Document.GetElementById("formButtonGreen");
s[0].InvokeMember("click");
Any one got any ideas?
Please note: I don't own the website so can't make changes to code behind webpage...
Thanks,
David
You should try using .Document.Body.GetElementsByTagName("input") which should help you get the button element and later you can use InvokeMember("click") on that element.
This will return a collection of matching elements, so if there are more than one you will have to identify it from the attributes by looping over it and then trigger for the one you need.
Instead of clicking the button, just submit the form itself.
jQuery wise, this is:
$("#my_form").submit();
Or you coulkd use any other means to select that Form. By class, parent element, tag name, ...

Categories

Resources