Is there anything wrong with my code? My if else statement is not working.
<%
String pages = request.getParameter("page");
%>
<input type="hidden" id="page" value="<%=pages%>"/>
<div class="navbar navbar-fixed-bottom">
<div class="navbar-inner">
<a class="brand" href="index.jsp">PeachMangoPie</a>
<ul class="nav pull-right">
<li <%if(pages=="papoy"){out.write("class='active' ");}%>>Papoy</li>
<li class="divider-vertical"></li>
<li <%if(pages=="chuckie"){out.write("class='active' ");}%>>Chuckie</li>
<li class="divider-vertical"></li>
<li <%if(pages=="dutchmill"){out.write("class='active' ");}%>>Dutch Mill</li>
<li class="divider-vertical"></li>
<li <%if(pages=="icecream"){out.write("class='active' ");}%>>Ice Cream</li>
<li class="divider-vertical"></li>
<li <%if(pages=="chicken"){out.write("class='active' ");}%>>Chicken</li>
<li class="divider-vertical"></li>
<li <%if(pages=="straberrycake"){out.write("class='active' ");}%>>Strawberry-Cake</li>
</ul>
</div>
</div>
You need to use the .equals method to test for string equality.
Try this instead:
<li <%if(pages.equals("papoy")){out.write("class='active' ");}%>>Papoy</li>
To fix your code: use equals to compare Strings (as shown in Harshal Pandya's answer).
To really fix your code: stop using scriptlets as explained here: How to avoid Java code in JSP files?. Rewrite all this using EL, JSTL and JavaScript. I wrote a basic example on this to omit all that hard-to-maintain scriptlet and HTML code:
<script type="text/javascript">
window.onload = function() {
var page = '<c:out value="${param.page}" />';
var ulOptions = document.getElementById('ulOptions');
var liItems = ulOptions.getElementsByTagName("li");
for(var i = 0; i < liItems.length; i++) {
var liItem = liItems[i];
var a = liItem.getElementsByTagName("a")[0];
if (a !== undefined && a.innerText.toLowerCase() === page) {
liItem.setAttribute("class", "brand");
}
}
};
</script>
<input type="hidden" id="page" value="${param.page}"/>
<div class="navbar navbar-fixed-bottom">
<div class="navbar-inner">
<a class="brand" href="index.jsp">PeachMangoPie</a>
<%--
provided id for ul HTML component in order to ease
JavaScript onload function development
--%>
<ul id="ulOptions" class="nav pull-right">
<li>Papoy</li>
<li class="divider-vertical"></li>
<li>Chuckie</li>
<li class="divider-vertical"></li>
<li>Dutch Mill</li>
<li class="divider-vertical"></li>
<li>Ice Cream</li>
<li class="divider-vertical"></li>
<li>Chicken</li>
<li class="divider-vertical"></li>
<li>Strawberry-Cake</li>
</ul>
</div>
</div>
Explanation of the provided code:
${param.page} replaces request.getParameter("page");
window.onload = function() { ... }; defining a JavaScript function to execute after loading the page (more info: onload Event).
<c:out> will print text directly on the generated HTML. More info: <c:out>.
document.getElementById returns an HTML element by its id (the function name explains this pretty straightforward).
getElementsByTagName returns a NodeList that contains all the inner HTML elements with the corresponding tag name (the function name explains this pretty straightforward).
for(var i = 0; i < liItems.length; i++) traverse all the <li> elements inside ulOptions.
liItem.getElementsByTagName("a")[0] as explained before, get the <a> element in position 0.
a !== undefined && a.innerText.toLowerCase() === page verifying that a exists (this for those <li> without the <a> element inside) and verifying the inner text against the page request parameter.
This is better approach (without scriptlets):
<li <c:out value="${param.page=='papoy'?'class=active':''}"/>">
Papoy
</li>
Related
I have written this loop below. It executes perfectly fine in the first iteration; however, in the second iteration, it returns the following error:
Unable to locate element:
{"method":"xpath","selector":"html/body/header[2]/div[2]/nav/ul/li[2]/a"}`
Command duration or timeout: `120.06` seconds
The loop code is mentioned below:
Workbook w2;
w2 = Workbook.getWorkbook(new File("C:\\Users\\pcs\\Desktop\\flightdata.xls")); //flight data destintion location will be same as source from flight data.
Sheet s2 = w2.getSheet(0);
for (k = 1; k < s2.getRows(); k++)
{
//redeem flow
d1.findElementByXPath("html/body/header[2]/div[2]/nav/ul/li[2]/a").click();
d1.findElementByXPath("html/body/header[2]/div[2]/nav/ul/li[2]/ul/li[3]/a").click();
d1.findElement(By.xpath("html/body/section/div[1]/form/div/div[2]/div[1]/div/div[1]/input")).sendKeys(s2.getCell(0, k).getContents());
//pause for list to be populated
try
{
Thread.sleep(1000L);
}
catch (Exception e)
{
}
//Get all items in autocomplete list
List<WebElement> items1 = d1.findElements(By.xpath("html/body/ul/li[3]/a"));
//Look for item
for( i= 0; i <items1.size();i++)
{
if(items1.get(i).getText().contains(s2.getCell(0, k).getContents()))
{
items1.get(i).click();
break;
}
}
//calendar handling
d1.findElementById("checkin").click();
d1.findElementByXPath("html/body/div[2]/div[2]/div/a/span").click();
d1.findElementByXPath("html/body/div[2]/div[2]/table/tbody/tr[3]/td[3]/a").click();
//Select Number of Rooms
d1.findElementById("roomscount").sendKeys("1");
//Select Room type
d1.findElementById("roomtype").sendKeys("Single");
//Occupant's Nationality
d1.findElementById("nationality").sendKeys("India");
//Click search button
d1.findElementByXPath("html/body/section/div[1]/form/div/div[2]/div[4]/input").click();
//after 2 min wait
d1.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
POST SEARCH HTML PAGE
<!DOCTYPE html>
<html>
<head>
<body class="" ondrop="return false;" ondragstart="return false;" onunload="" onpageshow="if (event.persisted) noBack();" onload="noBack();">
<header>
<div class="logo">
<div class="right">
<ul class="login">
<nav class="links">
<ul>
<li>
<li>
Redeem sMiles
<ul>
<li class="pointer sprite"> </li>
<li class="flight">
<li class="hotel">
<a href="hotel.html?action=hotels">
<span class="sprite"> </span>
Hotels
</a>
</li>
<li class="smiles">
</ul>
</li>
</ul>
</nav>
<div class="clear"></div>
</div>
<div class="clear"></div>
</header>
<div class="clear"></div>
<script src="/fm/travel/js/hotel.js" type="text/javascript">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link type="text/css" rel="stylesheet" href="/fm/styles/demo_table_jui.css">
<link rel="stylesheet" href="/fm/travel/styles/ui-lightness/jquery-ui-1.10.4.css">
<link rel="stylesheet" href="/fm/travel/styles/ui-lightness/autocomplete.css">
<script src="/fm/travel/js/jquery-1.10.2.js" type="text/javascript">
<script src="/fm/travel/js/jquery-ui-1.10.4.js" type="text/javascript">
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
<script type="text/javascript">
<script type="text/javascript">
<script type="text/javascript">
<div id="loader" style="display: none;">
<div id="modifySearchBlock" style="display: block;">
<div class="clear"></div>
<footer>
<script src="/fm/travel/js/jquery.js">
<script src="/fm/js/bootstrap.min.js">
<script src="/fm/js/jquery.meanmenu.js">
<script>
<script src="/fm/js/jquery.simpleGal.js">
<script>
<script src="/fm/js/owl.carousel.js">
<script>
<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>
<ul id="ui-id-1" class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all " tabindex="0" style="display: none;"></ul>
</body>
</html>
The above code belongs to the page where I return once search is completed.
Again I need to go to the below link to do the search:
<li class="flight">
<li class="hotel">
<a href="hotel.html?action=hotels">
<span class="sprite"> </span>
Hotels
</a>
</li>
<li class="smiles">
</ul>
</li>
The above code belongs to the link which I need to click. please provide same suggestions.
First you should have a look to other selector than xpath which is unreadble and can be dangerous, here you will a lot a way to find elements. For example cssSelector is a very reliable way to find element.
Another advantage is that your code become more readable.
If I understand, the first iteration no problem, then the seconde one, this is the click on the dropdown at the top of your page that cause the crash.
A possible solution is that your page is not come back to its original state at the end of your loop. You could refresh the page at the end of the loop:
driver.navigate().refresh();
Or check in which state you are at the end of the loop.
Hope that helps.
Well, the problem which my code was facing is that when search gets finished, I was trying trying to click the web elements with the same old xpaths. Actually, on close analysis I found that the xpaths of the same webelements on the results page got altered slightly due to which my script was not able to recognize the elements on new location.
Hence, i just changed the xpaths and problem got resolved.
I am new to HtmlUnit and I don't know how to get the text inside the [...]
A part of my html file:
<ul ......somethin....>
<li data-role="list-divider" role="heading" style="font-size:16px;" class="ui-bar-f">
INFORMATION_LINE_1
</li>
<li data-theme="d" class="ui-li ui-btn-icon-right ui-btn-up-d ui-odd-match-column ">
<div class="ui-btn-inner ui-li">
<div class="">
<div class="ui-btn-text">
<a href="/x/cxntay/13113/ndzvsssl/g1" class=" ui-link-inherit ui-link-hover">
<h3 class="ui-li-heading">
<span class="xheader">INFORMATION_LINE_2</span>
<span class="label live">INFORMATION_LINE_3</span>
</h3>
<div class="ui-live-scores">
<span class="team1-scores">
<span class="ui-team-name">INFORMATION_LINE_4</span>
<span style="font-weight:bold">INFORMATION_LINE_5</span>
</span>
<span>INFORMATION_LINE_6</span>
</div>
</a>
</div>
</div>
</div>
</li>
</ul>
Now, I want to retrieve "INFORMATION_LINE_X"(1,2...6) in between these tags..
This is what I tried:
List<HtmlUnorderedList> ls = (List<HtmlUnorderedList>) page.getByXPath("/ul");
List<DomNode> dls = ls.get(0).getChildNodes();
System.out.println(dls.get(0).getFirstByXPath("//li[#data-role='list-divider']/text()");
I just tried to get INFORMATION_LINE_1
But it printed null. I need to get all the INFORMATION_LINES.
It is better to use just XPath rather than mixing it with HTMLUnit methods. Something like this should work to get you the first information line:
HtmlElement e = page.getFirstByXPath("//li[#data-role='list-divider']");
System.out.println(e.asText());
In order to fetch the other information lines you should follow the same approach but changing the XPath string.
Bear in mind you should always debug the page by taking a look at the code by printing the output of page.asXml(). If you use a real browser you are not actually seeing exactly the same as HTMLUnit is seeing. You can stumble with differences particularly if the page executes JavaScript.
I'm trying to find out the xpath for resource manager element, when I tried with this code,
driver.findElement(By.xpath("Resource Manager xpath")).click(), I turned up with error saying unable to find the element.
<div class="os-titlebar navbar navbar-inverse">
<div class="navbar-inner">
<div class="container">
<ul class="nav menu-primary os-navbar-icon">
<ul class="nav context-menu" style="">
<ul class="nav os-navbar-icon os-titlebar-shortcuts pull-right os_shortcuts">
<li class="os-navbar-icon-home selected">
<li class="os-navbar-icon-quicklaunch os_quick_start">
<li class="os-navbar-icon-resourcemanager">
<li class="os-navbar-icon-apptray">
<li class="os-navbar-icon-notifications">
<li class="os-navbar-icon-minimise-close">
</ul>
<form class="navbar-search pull-right ui-os-search-form" action="">
<ul class="nav os-navbar-icon os-desktop-navigation" style="left: 407.5px;">
</div>
Resource Manager xpath is not a valid xpath expression.
This should work:
driver.findElement(By.xpath("//li[#class='os-navbar-icon-resourcemanager']")).click()
Use css selector instead of xpath. Also an example of WebDriverWait
WebDriverWait wait = new WebDriverWait(driver,300/*timeout in seconds*/);
By findBy = By.cssSelector("li.os-navbar-icon-resourcemanager");
wait.until(ExpectedConditions.elementToBeClickable(findBy)).click();
you may face "Unable to find element" only in two case for sure.
1.The Element is yet to Load
- Put some wait here.
2. You may try to locate the element wrongly .
- Double Check your Xpath/ID(what ever)
- Make sure you are in the same frame where the element is present.If not, switch to the frame then.
<div id="sbGlobalNav" class="">
<div id="sbGlobalNavContent">
<div id="sbGlobalNavRightContent">...</div>
<div id="sbGlobalNavLeftContent">
<ul id="globalNavMenu">
<li class="globalNavSeparator firstSeparator">..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li class="globalNavDropdown">
<span>Answer</span>
<ul class="globalNavDropdownContainer" style="display: none;">
<li>..</li>
<li>Daily Polls</li>
<li>..</li>
</ul>
</li>
<li class="globalNavDropdown">..</li>
<li class="globalNavSeparator">..</li>
<li class="globalNavDropdown" id="globalNavRewards">..</li>
<div class="clear"></div>
In this I need to find and click Daily Poll link using Selenium webdriver(java) but I was unable to do it.
What I did is:
Actions builder = new Actions(driver);
builder.moveToElement(driver.findElement(By.xpath("//div[#id='sbGlobalNav']//span[text()='Answer']"))).build().perform();
driver.findElement(By.linkText("Daily Polls")).click();
Check it, whether you have to so something to trigger that element out. Javascript maybe, by mouse over ?
Try this:
driver.findElement(By.xpath("//*[text()='Daily Polls']")).click();
It might work.
I have a tree generated with JSTree in my JSP page (part of a Struts2 webapp) as follows:
<div class="panel">
<div id="demo1" class="demo">
<ul>
<li id="node"><s:property value="product"/>
<ul>
<li id="node">
Dependents
<ul>
<s:iterator value="dependentsList" id="dependent">
<li id="node">
<a href="#">
<s:property value="productName"/></a>
<ul>
<li>
<a href="#">
Version Number: <s:property value="version" />
</a>
</li>
<s:if test="documentationLink != ''">
<li>
<a href="<s:property value="documentationLink" />">
Link to Product Documentation
</a>
</li>
</s:if>
</ul>
</li>
</s:iterator>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<script type="text/javascript" >
$(function () {
$("#demo1").jstree(
{
"core" :
{
"initially_open" : [ "#node" ]
},
"themes" :
{
"theme" : "default",
"icons" : false
},
"plugins" : [ "themes", "html_data", "ui"]
});
});
</script>
Thing is the links to product documentation show up on my browser (I tried using both Firefox and Internet Explorer) on the bottom status bar, but when I click on them, nothing pops up (I checked my HTML source code, and the anchor tags are showing the correct URL links). Could anyone figure out why my links aren't working? I am using both the latest versions of JQuery and JSTree. Thanks!
I got the links to work after removing the UI plugin, I guess the UI plugin doesn't like to work with HTML links...