Can't click button with selenium java - java

I had some success prior to this using below code.
driver.findElement(By.xpath("//xpath")).click();
driver.findElement(By.xpath("//div[#id='container']/div[#id='main']/div[#id='columnOne']/div[#class='ng-scope']/div[#class='content ng-scope']/div/div[#class='ng-isolate-scope']/div[#class='tab-content']/div[#class='tab-pane ng-scope active']/div[#class='ng-scope']/div[#id='uploadRequests']/div[#id='fileUploadPanel']/div[#class/span[#class='btn btn-primary']='panel-body']/div/div[#class='panel panel-default']/div[#class='panel-heading clearfix']/div[#class='pull-left']/label")).click();
Here is the html:
<div class="panel-body">
<div>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left">
<label for="inputFile"><input class="hidden" type="file" name="inputFile" id="inputFile" on-change-action="addFile" multiple="">
<span class="btn btn-primary xh-highlight"><i class="glyphicon glyphicon-plus"></i>Add</span>
</label>
</div>
<div class="pull-right ng-hide" ng-show="files.length > 0"><button ng-click="removeAll()" class="btn btn-primary"><i class="glyphicon glyphicon-remove"></i>Clear All</button></div>
</div>
<!-- ngRepeat: file in files -->
<div class="panel-body ng-hide" ng-show="progressBar">
<div>
<div class="progress-striped active progress ng-isolate-scope" value="uploadProgress" type="info">
<div class="progress-bar progress-bar-info" ng-class="type && 'progress-bar-' + type" role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" ng-style="{width: (percent < 100 ? percent : 100) + '%'}" aria-valuetext="%" aria-labelledby="progressbar" ng-transclude="" style="width: 100%;"></div>
</div>
</div>
<div>
<button class="btn btn-primary" ng-click="progressBar = false">Continue</button></div>
</div>
</div>
</div>
</div>
I usually try By.className(className), By.id(id), By.name(name), By.linkText(linkText) before By.xpath, but even here as a last resort I'm not able to click on an "Add" files button after I log onto a site.

Try to avoid of using xpath. There are very few situations, when there is no possibility to use another selectors, like css selectors or classes. Also there is not enough HTML code to find out why your xpath doesn't work. Please add more info.
PS try this:
driver.findElement(By.xpath("//input[#id='inputFile']/span[#class='btn btn-primary']")).click();

Related

NoSuchElementException - junit test error

I am using selenium junit testing.
If i try with selenium ide, the test goes well, but with junit it gives me this error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#firstName"}
I think that the span doesn't redirect to the page it should (but in normal schedule it does).
#Test
public void adminCreateDoc() {
driver.get("http://localhost:8080/login");
driver.manage().window().setSize(new Dimension(550, 706));
driver.findElement(By.linkText("Accesso amministratori")).click();
driver.findElement(By.id("username")).sendKeys("8245");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("prova1");
driver.findElement(By.cssSelector(".btn")).click();
driver.findElement(By.id("btn_createDoc")).click();
driver.findElement(By.id("firstName")).click();
driver.findElement(By.id("firstName")).sendKeys("Marco");
driver.findElement(By.id("lastName")).click();
driver.findElement(By.id("lastName")).sendKeys("Battiato");
driver.findElement(By.id("doc_type")).click();
driver.findElement(By.id("doc_type")).sendKeys("Cardiologo");
driver.findElement(By.id("id")).click();
driver.findElement(By.id("id")).sendKeys("855555");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("prova1");
driver.findElement(By.cssSelector(".glyphicon-send")).click();
}
I've tried with xpath, but without success...
HTML page with span redirection:
<body>
<div class="container text-center">
<div align="center">
<h2>Gestione dottori</h2>
<table class="table table-striped table-responsive-md">
<tr>
<th>ID</th>
<th>Nome</th>
<th>Specialit&agrave</th>
</tr>
<tr th:each="doc: ${listDoc}">
<td th:text="${doc.getId()}"></td>
<td>Dr. <span th:text="${doc.getFirstName()}"></span> <span th:text="${doc.getLastName()}"></span></td>
<td th:text="${doc.getDoc_type()}"></td>
</tr>
</table>
<a th:href = "#{/admin_createdoc}"><span id="btn_createDoc" class="plus bg-dark" >+</span></a>
<hr>
<div class="col col-lg-2 align-self-center">
<div class="p-1">
<form th:action="#{/admin_logout}" method=post>
<button name="btn_logout_profile" id="btn_logout_profile"
type="submit" class="btn btn-primary">Log Out</button>
</form>
</div>
</div>
</div>
</div>
</body>
Which redirect to this page:
<body>
<div class="container">
<div class="d-flex align-items-center justify-content-start">
<form th:action="#{/admin_homepage}" method=get>
<button name="btn_back_profile" id="btn_back_profile" type="submit"
class="btn btn-info">
<span class="fas fa-chevron-left"></span>
</button>
</form>
</div>
<br>
<div style='text-align: center'>
<form class="well form-horizontal" action="#"
th:action="#{/saveDoctor}" th:object="${doc}" method="POST"
id="contact_form">
<fieldset>
<!-- Form Name -->
<legend>
<center>
<h2>
<b>Doctor Creation Form</b>
</h2>
</center>
</legend>
<br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">First Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="first_name"
th:field="*{firstName}" placeholder="Doc First Name"
class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="last_name"
th:field="*{lastName}" placeholder="Doc Last Name"
class="form-control" type="text" required>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Type</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-list"></i></span> <input name="doc_type"
th:field="*{doc_type}" placeholder="Doc Type"
class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Id</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="id"
th:field="*{id}" placeholder="Doc ID" class="form-control"
type="number" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input
th:field="*{password}" name="doc_password"
placeholder="Doc Password" class="form-control" type="password"
required>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group" align="center">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<br>
<button type="submit" class="btn btn-warning">
SUBMIT <span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
</form>
<div>
<form th:action="#{/admin_logout}" method=post>
<button name="btn_logout_profile" id="btn_logout_profile"
type="submit" class="btn btn-primary">Log Out</button>
</form>
</div>
</div>
</div>
</body>
Thank you for your time!
The failure is happening on this line
driver.findElement(By.id("firstName")).click();
ID as a CSS selector is #firstName. Since this is right after a page transition, my guess is that the page isn't fully loaded before the next line of code is run. This can sometimes happen on a modern site where the page is loaded but there's still stuff being loaded asynchronously in the background. The fix is to add a wait, specifically a WebDriverWait, to the following line. That is one option...
Instead of adding a wait piecemeal when it's found that you need it, I prefer to write helper methods that take care of common actions like click(), sendKeys(), etc. and then let those methods take care of the specific waits for me.
public void click(By locator) {
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(locator)).click();
}
public void sendKeys(By locator, String text) {
findElement(locator).sendKeys(text);
}
public WebElement findElement(By locator) {
return new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(locator));
}
Then you can change your script to
#Test
public void adminCreateDoc() {
driver.get("http://localhost:8080/login");
driver.manage().window().setSize(new Dimension(550, 706));
click(By.linkText("Accesso amministratori"));
sendKeys(By.id("username"), "8245");
sendKeys(By.id("password"), "prova1");
click(By.cssSelector(".btn"));
click(By.id("btn_createDoc"));
sendKeys(By.id("firstName"), "Marco");
sendKeys(By.id("lastName"), "Battiato");
sendKeys(By.id("doc_type"), "Cardiologo");
sendKeys(By.id("id"), "855555");
sendKeys(By.id("password"), "prova1");
click(By.cssSelector(".glyphicon-send"));
}
which I think makes it more readable, adds waits to everything in case it's needed with no extra code, and so on...
The next level is using the Page Object Model to contain the locators and methods for each page. Then your code gets cleaned up significantly, makes it near-human readable, and MUCH easier to manage.

Skipping over inputting value to drop down menu when not available

Depending on who logs in the page changes from a field having a drop down menu to the field not having a drop down menu and I want my program to ignore that field when the drop down menu is not available. What I have now is this (customCoverageCell targets a cell in Excel)
Select dropDown = new Select(driver.findElement(By.xpath("//*[contains(text(), '"+ customCoverageCell +"')]/following::select")));
if((!customValueCell.equals("") && !driver.findElements(By.xpath("//*[contains(text(), '"+ customCoverageCell +"')]/following::select")).isEmpty())){
dropDown.selectByValue(customValueCell);
}
but it will try to change the drop down menu.
I've tried this
Select dropDown = new Select(driver.findElement(By.xpath("//*[contains(text(), '"+ customCoverageCell +"')]/following::select")));
if((!customValueCell.equals("") && driver.findElements(By.xpath("//*[contains(text(), '"+ customCoverageCell +"')]/following::select")).isEnabled())){//also tried isDisplayed and isSelected just to see if it actually would do anything
dropDown.selectByValue(customValueCell);
}
How would I get it to not try to input a value without making sure the value in excel is blank?
Here is the HTML in question:
WITHOUT DROP DOWN
<div class="wrap-padding-sm">
<div class="threeCols">
<div class="colContent">
<div class="sub-colContent">
<span class="checkmark-grey">
</span>
<span class="checkTitle">Third Party (THIS IS WHERE I NEED TO TARGET AND WORK FROM)
</span>
</div>
<div class="sub-colContent">Limit:
<span class="amount-midCol">$$$$$$$$$$$$
</span>
</div><span class="scroogeMsg h7 mobile-show">Some text</span>
</div>
<div class="colContent">
<a data-toggle="collapse" class="margin-R10" data-target="#cust_standard_scrooge_0">
<span>What this covers
</span>
</a>
<a data-toggle="collapse" data-target="#cust_standard_scrooge_0" class="btn-accordian collapsed"> </a>
</div>
</div>
<div id="cust_standard_scrooge_0" class="scrooge-wrap collapse">
<p>Some text
</p>
</div><span class="scroogeMsg h7 mobile-hide">Some text</span>
</div>
WITH DROP DOWN
<div class="wrap-padding-sm">
<div class="threeCols">
<div class="colContent">
<div class="sub-colContent">
<span class="checkmark-grey">
</span>
<span class="checkTitle">Third Party (THIS IS WHERE I NEED TO TARGET AND WORK FROM)
</span>
<span class="checkTitle_sub">Some text
</span>
</div>
<div class="sub-colContent">
<div class="select-dropWrap">
<div id="h_abc194" class="form-group form-group-lg "><label for="changeScrooge:h_abc161:0:h_abc194:select-one-menu" class="control-label">Limit: </label>
<div class="select-dropMenu ">
<div class="selector uniform-select fixedWidth" id="uniform-changeScrooges:h_abc161:0:h_abc194:select-one-menu"><span style="user-select: none;">1000000</span><select id="changeScrooges:h_abc161:0:h_abc194:select-one-menu" name="changeScrooges:h_abc161:0:h_abc194:select-one-menu" class="form-control input-lg " size="1" onchange="mojarra.ab(this,event,'valueChange','changeScrooges:custom_standard_scrooges','changeScrooges:custom_standard_scrooges changeScrooges:customAcceptDeclinePNL',{'onevent':recommendedScroogeAfterAJAX})">
<option value="1000000" selected="selected">1000000</option>
<option value="2000000">2000000</option>
</select></div>
</div>
</div>
</div>
</div><span class="scroogeMsg h7 mobile-show">Some text</span>
</div>
<div class="colContent">
<a data-toggle="collapse" class="margin-R10" data-target="#cust_standard_scrooge_0">
<span>What text?
</span>
</a>
<a data-toggle="collapse" data-target="#cust_standard_scrooge_0" class="btn-accordian collapsed"> </a>
</div>
</div>
<div id="cust_standard_scrooge_0" class="scrooge-wrap collapse">
<p>Some text
</p>
</div><span class="scroogeMsg h7 mobile-hide">Sme text</span>
</div>
All the black spots are just text fields that had to be blacked out
This is the small trick that i always used to find the existence of an element.
if(driver.findElements(By.xpath("")).size()>0)
{
//Element actually exists
//Do the Stuff
}
else
{
//Element doesn't exist
//Do the stuff if any
}
Hope this helps you. Thanks.

How to display the dynamic text availalble between div tags in selenium webdriver using JAVA

I have been trying to automate the password reset functionality. So when the email is available we get a message and when not another message, both are in the same tag but dynamic depending on the email id. How to display this dynamic text?
The source code is
if($.trim(response) == '1'){
$(".resultreset").html("<div class='alert alert-success'>New Password sent to "+resetemail+", Kindly check email</div>");
}else{
$(".resultreset").html("<div class='alert alert-danger'>Email Not Found</div>");
} }); });
The tags are like
<div class="resultreset">
<div class="alert alert-danger">Email Not Found</div>
</div>
and
<div class="resultreset">
<div class="alert alert-success">New Password sent to "xxx#xxx.com", Kindly check email</div>
</div>
How to get the text "Email Not Found" or New Password sent to "xxx#xxx.com", Kindly check email and display using JAVA in selenium webdriver.
I have tried to locate it using the xpath .//*[#id='passresetfrm']/div[1]/div/text(), but the webdriver is not able to locate the element.
Also tried with driver.findElement(By.classname("alert")).gettext();, even this is not recognized.
It locates the class, but not the message.
The complete source code for the forgot password section
<div id="ForgetPassword" class="modal wow fadeIn animated animated in" tabindex="" role="dialog" aria-labelledby="ForgetPassword" aria-hidden="true" style="visibility: visible; animation-name: fadeIn; display: block; padding-right: 17px;">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss="modal" aria-hidden="true">
<span class="ink animate" style="height: 21px; width: 21px; top: 2.5px; left: -5.56665px;"></span>
×
</button>
<h4 class="modal-title">
<i class="fa fa-asterisk"></i>
Forget Password
</h4>
</div>
<div class="modal-body">
<form id="passresetfrm" method="POST" action="" accept-charset="UTF-8" onsubmit="return false;">
<div class="resultreset">
<div class="alert alert-danger">Email Not Found</div>
</div>
<div class="input-group">
<input id="resetemail" class="form-control" placeholder="your#email.com" name="email" required="" type="text">
<span class="input-group-btn">
<button class="btn btn-primary resetbtn" type="submit">
<span class="ink animate" style="height: 62px; width: 62px; top: -98.7167px; left: -11.5167px;"></span>
Reset
</button>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
Identify the element and use getText to get the embedded text in that tag. Below code might give you some idea.
webElement result = driver.findElement(by.xpath("//div[#class='resultreset']/div"))
String message = result.getText();
Hope this helps. Thanks.
I'm not sure why getText() is not working for you, but can you try getAttribute("textContent") ?
String textToVeify = driver.findElement(By.classname("alert")).getAttribute("textContent");

instead of clicking on the element it clicks on the most top-left side of the window

I am using Java and Selenium to write a test. I have an element (a drop down menu) that I want to click on that I used action.click, elemnet.clcik javascript executor. But instead of the element they all click on the most top-left side of the window.
I opened developer tool window and checked my xpath that I finding the element with and it's correct, i mean when I copy paste the xpath at the DOM it shows the element. why do they click on top-left side of the window?
below is the snippet of the dom that the element is in there:
<div class="verde-form-row workflowTask-row even">
<h1><span class="by-label">Service</span>: Platinum <span class="unitOrLld">(Acres)</span></h1>
<form class="verde-form-fields fieldInfo-fields " data-task="">
<div data-create-with="" class="form-field-wrapper task-create-with">
<div class="select2-container select2-container-multi verde-select2 undefined" id="s2id_autogen11438">
<ul class="select2-choices">
<li class="select2-search-field">
<label for="s2id_autogen11439" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input select2-default" id="s2id_autogen11439" placeholder="" style="width: 290px;" aria-activedescendant="select2-result-label-11977"> </li>
</ul>
</div>
<input data-selector="" type="hidden" name="field" value="" tabindex="-1" class="select2-offscreen">
</div>
<div class="create-task-info">
<div class="task-comments">
<input type="text" name="comments" placeholder="Comments" value="">
<button type="button" data-action="cancel">Cancel</button>
</div>
<div class="task-lab">
<div class="form-field-wrapper" data-field-area="">
<input type="number" step="any" min="0" name="field_area" placeholder="Field Area" value="">
<label class="task-field-area-unit" data-field-area-units="">Acres</label>
</div>
<div data-lab-priority="" class="form-field-wrapper">
<div class="select2-container verde-select2 undefined select2-allowclear" id="s2id_autogen12036">
<a href="javascript:void(0)" class="select2-choice" tabindex="-1"> <span class="select2-chosen" id="select2-chosen-12037">Applied (Pre Buy)</span><abbr class="select2-search-choice-close"></abbr> <span class="select2-arrow" role="presentation"><b role="presentation"></b></span>
</a>
<label for="s2id_autogen12037" class="select2-offscreen"></label>
<input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-12037" id="s2id_autogen12037">
<div class="select2-drop select2-display-none select2-with-searchbox">
<div class="select2-search">
<label for="s2id_autogen12037_search" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" role="combobox" aria-expanded="true" aria-autocomplete="list" aria-owns="select2-results-12037" id="s2id_autogen12037_search" placeholder=""> </div>
<ul class="select2-results" role="listbox" id="select2-results-12037"> </ul>
</div>
</div>
<input data-selector="" type="hidden" name="lab_priority_type" value="11" tabindex="-1" title="" class="select2-offscreen">
</div>
<div data-lab-analysis="" class="form-field-wrapper"></div>
</div>
</div>
</form>
and this is my xpath:
//div[./h1[contains(text(),'Platinum')]]//span[text()='Applied (Pre Buy)']
a hint: when I click on any other parts of the window and then click on the element it works !!!

How to Submit HTML Form from Using Complex Forms with JSoup

Goal is to parse a HTML page from a site like Dice.com via Java JSoup and submit query text (like "Informatica") into that search form field.
I'm using Java JSoup but am open to other technologies, Java or otherwise.
Below is a snippet from Dice with sample of HTML form fields I'm trying to submit to.
I don't receive any HTML back from the System.out that shows that the search for "Informatica" was successfully posted to a form field. How do you do a POST with a search, given the Dice form listed below?
Connection.Response form = Jsoup.connect("https://www.dice.com").method(Connection.Method.GET).execute();
Document document = Jsoup.connect("https://www.dice.com/jobs")
.data("cookieexists", "false")
.data("search-form", "Informatica")
.data("q", "Informatica")
.data("search-field-keyword", "Informatica")
.cookies(form.cookies())
.post();
System.out.println(document);
Sample from Dice HTML source:
<form class="search-form" action="/jobs" method="GET" id="search-form">
<fieldset class="row">
<div class="col-xs-12">
<div class="form-group">
<strong class="title">Search across 77,990 Tech Jobs</strong>
</div>
</div>
<div class="col-md-6 col-sm-5">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><label for="search-field-keyword"
class="icon- magnifier"></label></div>
<input type="search" class="form-control input-lg" placeholder="Job title
or keywords" id="search-field-keyword" name="q" autofocus autocomplete="off">
</div>
<div class="help-block">job title, skills, keywords or company name</div>
</div>
</div>
<div class="col-md-3 col-sm-4">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><label for="search-field-location"
class="icon-compass-3"></label></div>
<input type="search" class="form-control input-lg" placeholder="Location"
id="search-field-location" name="l" autocomplete="off">
</div>
<div class="help-block">zip code, city or state</div>
</div>
</div>
<div class="col-sm-3">
<div class="row">
<div class="col-sm-12 col-xs-8">
<button type="submit" class="btn btn-primary btn-lg btn-block">Find Tech
Jobs</button>
</div>
<div class="col-sm-12 col-xs-4">
<div class="text-right help-block link-as"><a href="/jobs
/advancedSearch.html"><span class="icomoon-equalizer"></span> Advanced <span
class="txt-search">Search</span></a></div>
</div>
</div>
</div>
</fieldset>
</form>

Categories