Not able to click or select the value - selenium

I am stuck with the below scenario, trying to click or select the value from the field.
There are 2 fields "Type of Test" which is a dropdown, after selecting the value from dropdown "Body Part" field gets active.
Trying to select the value from "Body Part", but not able to click or select the value from the field.
I have exported the script from Selenium IDE, please let me know where to correct.
public class test {
private WebDriver driver;
private String baseUrl;
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://nyrp.opendr.com/search/client-search/pid/VFZSRk5FNVJQVDA9?script=javascript&badge=1";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test() throws Exception {
driver.get(baseUrl + "search/client-search/pid/VFZSRk5FNVJQVDA9?script=javascript&badge=1");
driver.findElement(By.id("typeoftest_1")).click();
new Select(driver.findElement(By.id("typeoftest_1"))).selectByVisibleText("MRA");
Thread.sleep(500);
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.id("bodypart_1"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("bodypart_1")).click();
driver.findElement(By.cssSelector("#bodyPartList_1 > li > div.mailval.")).click();
driver.findElement(By.cssSelector("a.search")).click();
}
private boolean isElementPresent(By id) {
// TODO Auto-generated method stub
return false;
}
}
Following is the HTML CODE for "Body Part" field:
<div id="bodypart_box_1">
<div style="position:absolute;left:185px;z-index: 20">
<ul class="parent">
<li>
<div id="main" class="mailval">events=Object { click=[1]}handle=function()
<input id="bodypart_1" class="bodypart" type="text" onfocus="if($(this).hasClass('disabled')){$(this).blur();}" readonly="readonly" value="Select One" name="bodypart_1" title="">
<input id="actualBodypart_1" type="hidden" value="" name="actualBodypart_1">
</div>
<ul id="bodyPartList_1" class="top sub bodyPartList" style="display: none;">olddisplay="none"
<li>
<div class="mailval " title="Head" originaltitle="Head">Head</div>events=Object { click=[1], mouseover=[1]}handle=function()
</li>
<li>
<div class="mailval " title="Neck" originaltitle="Neck">Neck</div>events=Object { click=[1], mouseover=[1]}handle=function()
</li>
<li>
<div class="mailval " title="Pelvis" originaltitle="Pelvis">Pelvis</div>events=Object { click=[1], mouseover=[1]}handle=function()
</li>
</ul>
</li>
</ul>
<div style="clear:both"></div>
</div>

Related

Show Post submit popup message in ASP.Net Core Razor page without controller

I have an ASP.Net Core Razor web application without controllers.
I have a form in my cshtml page and on Post/Submit I am calling an external API, which returns a success message or an error message. I want to show this message in my page as a popup.
I tried multiple things but failed. Here is my code.
In my "Index.cshtml"
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address"/>
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
In my Index.cshtml.cs
[BindProperty]
public string SubscriptionEmail { get; set; }
public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }
public async void OnPostNewsSubscription()
{
try
{
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = string.Empty;
using (HttpClient _httpClient = _httpClientFactory.CreateClient("PortalBasicHttpClient"))
{
if (!string.IsNullOrEmpty(SubscriptionEmail))
{
HttpRequestMessage _Request = new(HttpMethod.Post, _httpClient.BaseAddress + "Api/SaveSubscriptionEmail/" + SubscriptionEmail);
HttpResponseMessage _Response = await _httpClient.SendAsync(_Request);
if (_Response.IsSuccessStatusCode)
{
this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
}
else
{
this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = ex.Message;
}
}
My code behind is working fine, but not sure how to grace fully show this in the razor page using bootstrap.
looking forward for some guidance.
I tried using modal popup, but the text was not updated in the label I used in the modal popup and the pop-up disappeared with in few seconds, even though there was a "ok" button.
I also tried to use the java script method as mentioned in the following link https://www.aspsnippets.com/Articles/ASPNet-Core-Razor-Pages-Display-JavaScript-Alert-Message-Box.aspx
I will be great help if someone can help with a sample code.
Please debug your code and be sure the two properties actually contain the value you want.
The following working demo I just hard coded the two properties value for easy testing in the backend:
Index.cshtml
#page
#model IndexModel
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
#if (Model.ActionResultMessageText == string.Empty)
{
<script type="text/javascript">
window.onload = function () {
alert("#Model.ActionResultErrorMessageText");
};
</script>
}
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty]
public string SubscriptionEmail { get; set; }
public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }
public void OnGet()
{
}
public async void OnPostNewsSubscription()
{
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = "error";
}
}
Result:
If you want to use Bootstrap modal popup, change your page like below:
#page
#model IndexModel
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#Model.ActionResultErrorMessageText
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#if (Model.ActionResultMessageText == string.Empty)
{
<script type="text/javascript">
window.onload = function () {
$("#exampleModal").modal("show")
};
</script>
}
Result:

My web page is left without any reaction after the website is launched and the page is locked

I have web page and My web page is left without any reaction after the website is launched and the page is locked. Codes are as bellow:
#attribute [Authorize]
#inject IReciption _Reception;
<section class="p-top-10 p-bottom-10 bgcolor rtl">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="shortcode_modules">
<div class="modules__title">
<h3>Reception</h3>
#*<h3>RegReception<InfoBoxComponent StrMessage="#Message1"></InfoBoxComponent></h3>*#
</div>
<div class="text-center module--social">
<div class="social social--color--filled">
<ul>
<li>
<div>
<input type="text" #bind-value="#StrSerialNumber" placeholder="SerialNumber">
</div>
</li>
<li>
#if (!IsSaveLoading)
{
<button class="btn btn-primary" #onclick="(() => CheckTheSerial())" style="margin-top:15px;">Testing</button>
}
else
{
<button class="btn btn-primary" style="margin-top:15px;">
<i class="fa fa-spin fa-spinner"></i> Searching
</button>
}
</li>
#if (prodSrCls.Responses.Statue != LosacoWeb.Shared.Enumes.StatueResponse.NoStatus)
{
#if (prodSrCls.Responses.Statue == LosacoWeb.Shared.Enumes.StatueResponse.Success)
{
<br />
<li><h4><b class="primary">Group:</b> #prodSrCls.GoodsGroupItem_Name</h4></li>
<br />
<li><h4><b class="primary">Model:</b> #prodSrCls.Goods_GoodsName </h4></li>
}
#if (prodSrCls.Responses.Statue == LosacoWeb.Shared.Enumes.StatueResponse.Failed)
{
<br />
<li>
<h3>
<span class="danger icon-close"></span><b class="danger">
Serial Is not Correct
</b>
</h3>
</li>
}
}
</ul>
</div>
</div>
</div>
</div>
<!-- end .col-md-6 -->
</div>
<!-- end .row -->
</div>
<!-- end .container -->
</section>
And C# Programming Code Part Is As Bellow:
public bool IsSaveLoading = false;
private string serial;
public String StrSerialNumber
{
get
{
return serial;
}
set
{
serial = value;
TextChangedEvetFotCleaning();
}
}
ProdSerialClasses prodSrCls
= new ProdSerialClasses();
[Parameter]
public EventCallback<ProdSerialClasses> OnFindSerial { get; set; }
protected override async Task OnInitializedAsync()
{
IsSaveLoading = false;
}
My answer is that how I can resolve my problem. I have to use this code in a online shop project. My other pages work fine. but this page become lock after run.
Hi. Change second part to :
public bool IsSaveLoading = false;
public String StrSerialNumber = "0";
ProdSerialClasses prodSrCls = new ProdSerialClasses();
[Parameter]
public EventCallback<ProdSerialClasses> OnFindSerial { get; set; }
protected override async Task OnInitializedAsync()
{
IsSaveLoading = false;
}
you must add value to you variable StrSerialNumber = "0" because in can cause of error with null value.
I hope your code problem is solved this way.
You should also check for prolapse before using prodSrCls. If it is not null, you can use it. If you do not bet, you may still get the error.
#if(prodSrCls != null)
{
// your codes . . .
}
Please do not forget to confirm the answer.

how to differentiate the answers format(Checkbox or Textarea etc.) while working with for loop

I have a scenario where 15 questions are there and i do have to select the answer either by selecting radiobutton or checkbox or Yes/No button or have to enter some text in textarea.
My following code successfully selecting the answer randomly whether its a radio/checkbox or Yes/No button and displays the selected option as an answer along with question on console.
But how do i check if its textarea and need to enter something with 'sendKeys? And how do i select more than one checkboxes? And how do i display the answer Yes or No onconsole?
public void AssessmentTest() throws Exception
{
List<WebElement>totalQSN = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div"));
List<WebElement> mainQuestions = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div/div[2]/div"));
System.out.println("The Questions are::");
for(int i=0; i<totalQSN.size()-5; i++)
{
System.out.println("QUESTION:- " + mainQuestions.get(i).getText() + "["+ i +"]" );
Random rnd = new Random();
List<WebElement> subOptions = totalQSN.get(i).findElements(By.tagName("input"));
WebElement sValue = subOptions.get(rnd.nextInt(subOptions.size()));
sValue.click();
List<WebElement> subQsnList = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div/div[3]/div/span/span"));
System.out.println(subOptions.size());
for(int j=0; j<subOptions.size(); j++)
{
if(subOptions.get(j).isSelected())
{
String selectedAnswer= subQsnList.get(j).getText();
System.out.println("ANSWER: - " + selectedAnswer);
System.out.println("\n");
}
}
} }
HTML Code is as under for each type of question.
<div id="individualQuestionAnswerContainer147" class="individual-question-answer-container" style="display: block;" xpath="1">
<div class="individual-questions-count-container"></div>
<div id="questionContainer147" style="clear: both; float: left;"></div> //Contains Question
<div id="questionAnswerContainer147" class="answers-container"></div> //Contains Answers
</div>
If the question having checkboxes, the code is
<div id="individualQuestionAnswerContainer148" class="individual-question-answer-container" style="" xpath="2"> Contains 4 checkbox(divs)
<div class="individual-questions-count-container"></div>
<div id="questionContainer148" style="clear: both; float: left;"></div>
<div id="questionAnswerContainer148" class="answers-container" style="">
<div class="answer-text">
<span class="answer-text-inner btn-assessment-answer">
<input type="checkbox" name="Checkbox148" id="Checkbox449" class="radio-assessment-answer">
<span style="display: table;">
Good
</span>
</span>
</div>
<div class="answer-text">
<span class="answer-text-inner btn-assessment-answer">
<input type="checkbox" name="Checkbox148" id="Checkbox450" class="radio-assessment-answer">
<span style="display: table;">
Mold
</span>
</span>
</div>
<div class="answer-text"></div>
<div class="answer-text"></div>
</div>
</div>
If question having 2 buttons(Yes/No), the code is
<div id="individualQuestionAnswerContainer155" class="individual-question-answer-container" style="" xpath="7"> Contains 2 options Yes or No
<div class="individual-questions-count-container"></div>
<div id="questionContainer155" style="clear: both; float: left;"></div>
<div id="questionAnswerContainer155" class="answers-container" style="">
<input type="button" value="Yes" id="Button477" class="btnClass_155 btn-assessment-answer" style="">
<input type="button" value="No" id="Button478" class="btnClass_155 buttonClicked btn-assessment-answer">
</div>
</div>
If question having textarea, the code is
<div id="questionAnswerContainer38" class="answers-container" xpath="1">
<textarea maxlength="50000" rows="2" cols="100" id="FreeTextarea38"></textarea>
</div>
Try using this structure..Hope this helps.
public void AssessmentTest() throws Exception
{
List<WebElement>totalQSN = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div"));//Assuming this xpath is correct
List<WebElement> mainQuestions = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div/div[2]/div")); //Assuming this xpath is correct
System.out.println("The Questions are::");
for(int i=0; i<totalQSN.size()-5; i++)
{
System.out.println("QUESTION:- " + mainQuestions.get(i).getText() + "["+ i +"]" );
Random rnd = new Random();
String webeleTag=totalQSN.get(i).getTagName();
if(webeleTag.equals("input"))){
String webeleType=totalQSN.get(i).getAttribute("type");
switch(webeleType){
case:"checkbox":
//your code to select check box
case:"button":
//Only click event on answer
default:
}
}
else if(webeleTag.equals("textarea")){
//your code
}
else{
//Not text area,checkbox or radio something else
}
}
}
To detect if it is a text area, from the top of my head you can go
for .getTagName() this will return the tag of the element.
To get all the checkboxes you can use driver.findElements(By.id("questionAnswerContainer148")).toArray(new WebElement[0]) , this will return an array with the checkboxes and you can use some logic to click in the items you want from the list.
For the yes/no, I think that the driver.findElement(by).getAttribute("value") will return the content of the attribute.
Hope this helps you.

Getting access denied after a successfull authentication Spring Security with JDBC

After a successful authentication i get redirected to a access denied page.
WebSecurityContext
#Configuration
#EnableWebSecurity
public class WebSecurityContext extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN", "ROLE_CONTRIBUTOR","ROLE_ROOT")
.and()
.formLogin().loginPage("/admin/login")
.failureUrl("/admin/login/error")
.successHandler(new SuccessfulAuthHandler())
.loginProcessingUrl("/admin/login")
.defaultSuccessUrl("/admin")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/admin/login/logout");
}
#Bean(name = "passwordencoder")
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder(10);
}
SuccessHandler
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
final HttpSession currentSession = request.getSession();
final User user = userService.findByUsername(authentication.getName());
final List<Object> jObj = new ArrayList<>();
final List<Institution> institutions = institutionService.findAllByUserID(user.getId());
for(Institution i : institutions){
Map<String, Object> m = new HashMap<>();
m.put("name", i.getName());
m.put("id", i.getId());
jObj.add(m);
}
currentSession.setAttribute("userInInstitution", jObj);
currentSession.setAttribute("currentUser", user);
String servlet = "";
if(user.getRole() == ConstantsCommon.USER_ROLE_ADMIN){
servlet = DashBoardController.URL;
currentSession.setAttribute("dashboardServlet", servlet);
}else{
servlet = DashBoardController.URL;
currentSession.setAttribute("dashboardServlet", servlet);
}
if(jObj.size() > 1){
currentSession.setAttribute("institution",institutions.get(0));
}else{
currentSession.setAttribute("institution",institutions.get(0));
}
RedirectStrategy r = new DefaultRedirectStrategy();
r.sendRedirect(request,response, servlet);
}
Login HTML
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="pr-wrap">
<div class="pass-reset">
<label>
Enter the email you signed up with</label>
<input type="email" placeholder="Email" />
<input type="submit" value="Submit" class="pass-reset-submit btn btn-success btn-sm" />
</div>
</div>
<div class="wrap">
<p class="form-title">Sign In</p>
<form class="login" name="loginForm" method='POST'>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<input type="text" name="username" placeholder="Username"/>
<input type="password" name="password" placeholder="Password"/>
<input type="submit" name="submit" value="Sign In" class="btn btn-success btn-sm" />
<div class="remember-forgot">
<div th:if="${error}" class="alert alert-danger notificationMsg" role="alert">
<span th:text="${error}"></span>
</div>
<div th:if="${msg}" class="alert alert-success notificationMsg" role="alert">
<span th:text="${msg}"></span>
</div>
<!--<div class=" forgot-pass-content">-->
<!--Forgot Password-->
<!--</div>-->
</div>
</form>
</div>
</div>
</div>
What am I doing wrong here ?????? The user im logging in with has the role "ROLE_ADMIN". One thing i have also noticed is that my success handler doesn't even get triggered which suggest that mu authentication isn't successful but that can't be right because the password and username are 100% correct.

testing submit button with selenium webDriver

My html form contains multipl html tags such <form>
My html file: myFile.html
<body>
<div class="globalContainer">
<div class="test1" id="formM" width="848" height="720" method="post" name="devis" onreset="return vider();">
<div class="content-1" id="cadreGlob">
<div id="contentForm">
<div class="preview">
<div class="left_col">
<fieldset id="haut">
<label class="labelForm" id="labelPriorite">label1:</label>
<select id="selectPrio">
<option value="labT">subLabel11</option>
<option value="labP">subLabel12</option>
</select><p></p>
<form enctype="multipart/form-data" method="post">
<label class="labelForm" id="labelFile1">label2:</label>
<input id="upload1" type="file" name="file[]" />
</form>
</fieldset>
</div>
<div class="right_col">
<fieldset id="haut">
<form name="page">
<label class="labelForm" for="cb" id="labelPopulation">lebel3:</label>
<input type="checkbox" id="cb" name="cb" checked="checked" onclick="valid();showPop();" /><br />
<label class="labelForm" for="ta" id="labelMessage2">label4:</label>
<textarea disabled="true" id="ta" name="ta" cols="22" rows="9"></textarea>
<label class="labelForm" id="labelFile2" >label5:</label>
<input id="upload2" type="file" name="valider" id="butonParc" disabled="disabled"/>
</form>
</fieldset>
</div>
<div class="left_col">
<p></p>
<fieldset id="bas">
<label class="labelForm" id="labelServiceOp">label6:</label>
<select id="selectServOp">
<option value="def">subLabel61</option>
<option value="sec">subLabel62</option>
</select><p></p>
</fieldset>
</div>
<div class="right_col">
<p></p>
<fieldset id="bas">
<label class="labelForm" id="labelAdressage" >label7:</label>
<select name="ToutePopD" id="ToutePopD">
<option value="toujours">subLabel71</option>
<option value="parfois">subLabl72</option>
</select>
<select name="ToutePopA" id="ToutePopA">
<option value="toujours">subLabl73</option>
<option value="parfois">subLabel74</option>
</select>
</fieldset>
</div>
<div class="right_col"><p></p>
<form action="submit.html" id="sub" name="formValid">
<input type="submit" id="validation" value="validate" name="submit" />
</form> <p></p>
<script>
function vider()
{
document.getElementById("formM").value = "";
return false;
};
</script>
<input type="reset" id="cancel" value="Cancel"name="reset" />
</div>
</div>
</div>
</div>
</div>
</div>
</body>
My first problem
when i execute this command
...
...
this.driver.findElement(By.id("validation")).click();
...
...
My test is not switch to the url : submit.html
My submit.html
<body>
<h2><center>Form validation with Succee</center></h2>
</body>
My second problem:
When i execute the following code, i have an error : Unable to locate element : {"method":"id","selector":"sub"}
public class SeleniumTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private final StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
final Properties properties = System.getProperties();
this.baseUrl = properties.getProperty("base.url", "myIp:8080/project");
}
#Test
public void firefoxTest() throws Exception {
this.driver = new FirefoxDriver();
testSelenium();
verifyValidation(this.baseUrl +"submit.html");
}
private void testSelenium() throws Exception {
this.driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
this.driver.get(this.baseUrl + "myFile.html");
new Select(this.driver.findElement(By.id("formM")).findElement(By.xpath("//fieldset[#id='haut']/select[1]"))).selectByVisibleText("subLabel11");
this.driver.findElement(By.id("upload1")).sendKeys("myUrl\\myFile.txt");
this.driver.findElement(By.id("validation")).click();
}
private void verifyValidation(String urlValidation) {
String submit =
this.driver.findElement(By.id("sub")).getAttribute("action");
if (submit == urlValidation) {assertEquals("url problem : ", submit, urlValidation);
}
#After
public void tearDown() throws Exception {
this.driver.quit();
final String verificationErrorString = this.verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(final By by) {
try {
this.driver.findElement(by);
return true;
} catch (final NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
final Alert alert = this.driver.switchTo().alert();
final String alertText = alert.getText();
if (this.acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
this.acceptNextAlert = true;
}
}
}
I don't know why WebDriver can not find my id ! ?
Thanks for help !
For your 2nd issue,
it comes into my mind, when there is no submit.html file on your server, page
not found displays. Then, on that page, there is no "id" element -> you get
NoSuchElement Exception throws
There are 4 issues in your scripts
1 - Your xpath //fieldset[#id='haut']/select[0] is not correct, xpath starts from [1]
2 - There is no label "subLabel11", only "subLabl11" exists
3 - this.driver.findElement(By.id("sub")).getAttribute("action"); will return *full-url* (In this case myIp:8080/project/submit.html
4 - if (submit == urlValidation) will always return False since they are 2 objects in different memory location.
Suggest you change it to if (submit.equals(urlValidation))
Beside these above notes, I run your script well on my machine and there is no issue. Here's my script:
new Select(browser.getBrowserCore().findElement(By.id("formM")).findElement(By.xpath("//fieldset[#id='haut']/select"))).selectByVisibleText("subLabl11");
browser.getBrowserCore().findElement(By.id("upload1")).sendKeys("myUrl\\myFile.txt");
browser.getBrowserCore().findElement(By.id("validation")).click();
String submit =
browser.getBrowserCore().findElement(By.id("sub")).getAttribute("action");
System.out.println("submit: "+ submit);
if (!submit.equals("submit.html")) {
System.out.println("comparator: FALSE");
};
Here's the test result
2014-07-21 18:13:44 [main]-[INFO] Started Browser
2014-07-21 18:13:44 [main]-[INFO] Pause 500 ms
2014-07-21 18:13:45 [main]-[INFO] Opened url: http://myIP:8305/
submit: http://myIP:8305/submit.html
comparator: FALSE
2014-07-21 18:13:51 [main]-[INFO] Pause 500 ms
2014-07-21 18:13:51 [main]-[INFO] Quitted Browser
PASSED: stackOverFlowTest
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
For your first question, the below code work fine with me.
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.get("Your URL");
WebElement validate=driver.findElement(By.id("validation"));
validate.click();
driver.close();
}
Following is the code for your 2nd question:
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.get("Your URL");
WebElement element=driver.findElement(By.id("selectPrio"));
Select sel=new Select(element);
sel.selectByVisibleText("subLabel12");
driver.close();
}
Thank you all for tracks you give me.
I finally succeeded to solve my problem
For my first problem:
I had a mistake in the URL of my page submit.html
For my second problem:
when I execute the command: this.driver.findElement this.driver.findElement(By.id("validation")).click();
the page myFile.html where there is my id "sub" is not supported by the driver but submit.html
And then I made the switch back to my original page myfile.html and I have no error.
Thank you again!