I'm working on an application that will automatically click a button on a webpage using htmlunit in Java. Only problem is that that button is a javascript button, so the standard getInputByName() won't work. Any suggestions with dealing with this? The code for the button is included below.
<a class="vote_1" id="1537385" href="/javascript%3Avoid%280%29/index"><img src="/images/parts/btn-vote.gif" alt="Btn-vote" /></a>
In addition, here's the other code for voting.
<div id="content"><script type="text/javascript" src="/js/scriptFeeds/voteArticle.js"></script>
Which leads to the following javascript:
var pressed = new Array();
$j(document).ready(function() {
var nr = $j("input#number_of_articles").val();
for(var i=1; i<=nr; i++){
$j("a.vote_"+i).click(function(){
var article = $j(this).attr("id");
$j('#'+article).hide();
if (!pressed[article]) {
pressed[article] = "yes";
jQuery.post('/vote-article', {
_token: $j("#_token").val(),
article_id: article
},function(data) {
$j("span.numberOfVotes_"+data.id).html(data.votes);
}, "json");
}
return false;
});
}
});
Try using this addOn for firefox, it records your actions and generates the HTMLUnit code for the same. may be it could help.
http://code.google.com/p/htmlunitscripter/
There's nothing special about clickable images. Something like this should work:
button = page.getHtmlElementById( "1537385" ) ;
page = button.click() ;
HtmlUnit will then run the Javascript and return the updated page.
If the id attribute of the 'a' tag isn't constant, you may need to use XPath to grab it.
I have a very similar link on one of my pages. If you can call .click() on any HtmlElement, it should be able to run associated Javascript. Here is my code (generated from HtmlUnitScripter):
HtmlElement element4 = null;
Iterable<HtmlElement> iterable5 = page.getAllHtmlChildElements();
Iterator<HtmlElement> i6 = iterable5.iterator();
while(i6.hasNext())
{
HtmlElement anElement = i6.next();
if(anElement instanceof HtmlImage)
{
HtmlImage input = (HtmlImage) anElement;
String[] elements = "http://example.com/pages/powerbutton.png".split( "/" );
if(input.getSrcAttribute().indexOf(elements[elements.length-1] )> -1 )
{
element4 = input;
break;
}
}
}
HtmlPage page = element4.click();
Related
There is a button. When you click on this button, a drop down menu having two option appears. How to verify this scenario using selenium in java.
<div class="hpDropDownButton">
<button class="button ng-binding">Holidays Operation</button>
<ul>
<li>
<a class="ng-binding" ng-click="uploadHolidays()">Upload Holidays</a>
</li>
<li>
<a class="ng-binding" ng-click="deleteHolidays()">Delete Holidays</a>
</li>
</ul>
Click on the button
Now :-
Boolean dropdownPresent = driver.findElement("YOUR LOCATOR OF DROPDOWN").isDisplayed();
if(dropdownPresent==true)
{
System.out.println("Dropdown is appearing");
}
else{
System.out.println("Dropdown is not appearing");
}
Hope it will help you :)
You are asking to verify whole scenario. You need to first understand what Selenium-WebDriver is. Refer this tutorial for more explanation.
However you can follow below code,
WebDriver driver = new FirefoxDriver();
String appUrl = "your url";
driver.get(appUrl);
// maximize the browser window
driver.manage().window().maximize();
// upto code from your button
WebElement button_element = driver.findElement(button_locator);
button_element.click();
// to verify a drop down menu having two option appears
boolean flag = isPresent(dropdown_locator);
if (flag) {
// code bases on dropdown displayed
}
else {
// code bases on dropdown not displayed
}
To verify if element is present or not use this method
public boolean isPresent(String locator) {
return findElements(locator).size() > 0 ? true : false;
}
First of all collect all the Drop down values in List, List values = Upload Holidays#Delete Holidays
Then click on Dropdown WebElement, by using DropdownFieldName = driver.findElement(by.xpath(//button[#class='button ng-binding'])).click();
Take the couunt of dropdown values, by drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
Now you have expected DropDown values and count of Dropdown Values.
You can take a reference from below code:
checkDropDownValues(String DropdownFieldName, String values){
driver.findElement(By.xath(DropdownFieldName)).click();
WebElement drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
int numberOfDropDown = drptotalCount.size();
List<String> allDropDownValues = Arrays.asList(values.split("#"));
for (int colCount = 1; colCount <= numberOfDropDown; colCount++) {
boolean flag = false;
Actualvalue = driver.findElement(By.xpath(drptotalCount + "[.=" + allDropDownValues.get(colCount) +"]"])).getText();
String expectedValues = allDropDownValues.get(colCount);
if(expectedValues.equalIgnoreCase(Actualvalue))
{
flag = true;
}
Assert.assertTrue("Column values doesn't match", flag);
}
}
Click the button (which should be straight forward)
it seems you have some asynchronous call or a delay
Wait for the drop-down 'div.hpDropDownButton' is beeing displayed using WebDriverWait:
WebElement myDynamicDropDown = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.CssSelector("div.myDynamicDropDown")))
continue ..
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
I am trying to get the value of h1 as a string using selenium.
Here is the HTML javascript-
<script type="text/javascript">
$(window).load(function() {
var $windowHeight = $(window).height() -12;
$("#top").height($windowHeight);
$('h1').css({
'margin-top' : (($windowHeight) - $('h1').outerHeight())/2,
'margin-bottom' : (($windowHeight) - $('h1').outerHeight())/2,
'opacity' : '1.0',
'filter' : 'alpha(opacity = 100)',
});
$("#container").click(function(){
$("html, body").animate({
scrollTop: $windowHeight + 50
}, 1500);
})
});
$(window).on("debouncedresize", function( event ) {
var $windowHeight = $(window).height() -12;
$("#top").height($windowHeight);
$('h1').css({
'margin-top' : (($windowHeight) - $('h1').outerHeight())/2,
'margin-bottom' : (($windowHeight) - $('h1').outerHeight())/2
});
});
</script>
Here is what I've written in JAVA-
WebDriver driver = new FirefoxDriver();
driver.get("view-source:http://websitename.com/");
Thread.sleep(3000);
JavascriptExecutor js = null;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
}
js.executeScript("h1");
Not sure if I should be using JavascriptExecutor in the first place. I'd appreciate any help. Thanks
h1 is a tag on the page. Why do you try accessing it using JavascriptExecutor?
If you want to get text of the header h1 simply use such code
String text = driver.findElement(By.css("h1")).getText();
If you want to get an attribute of the tag use this code instead
String attr= driver.findElement(By.css("h1")).getAttribute(<attr-name>);
It works now! I was supposed to get the source of the page by using driver.getPageSource(); Not by driver.get("view-source:websitename.com/"). Stupid me. Thanks for the help! :)
I want to use JavaScript with WebDriver (Selenium 2) using Java.
I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:
$ ./go webdriverjs
My question: From which folder/location the command mentioned above will be run/executed?
Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.
The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.
If you want to run JavaScript code in Java WebDriver, do this instead:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
I like to do this, also:
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
} // else throw...
// later on...
js.executeScript("return document.getElementById('someId');");
You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.
The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:
1.
// returns the right WebElement
// it's the same as driver.findElement(By.id("someId"))
js.executeScript("return document.getElementById('someId');");
// draws a border around WebElement
WebElement element = driver.findElement(By.anything("tada"));
js.executeScript("arguments[0].style.border='3px solid red'", element);
// changes all input elements on the page to radio buttons
js.executeScript(
"var inputs = document.getElementsByTagName('input');" +
"for(var i = 0; i < inputs.length; i++) { " +
" inputs[i].type = 'radio';" +
"}" );
JavaScript With Selenium WebDriver
Selenium is one of the most popular automated testing suites.
Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver(); // This opens a window
String url = "----";
/*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
driver.findElement(By.name("j_password")).sendKeys("yashwanth#123");*/
JavascriptExecutor jse = (JavascriptExecutor) driver;
if (jse instanceof WebDriver) {
//Launching the browser application
jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[#name='j_password']")).sendKeys("admin");
//Opend Site and click on some links. then you can apply go(-1)--> back forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();
jse.executeScript("window.history.go(0)");
jse.executeScript("window.history.go(-2)");
jse.executeScript("window.history.forward(-2)");
String title = (String)jse.executeScript("return document.title");
System.out.println(" Title Of site : "+title);
String domain = (String)jse.executeScript("return document.domain");
System.out.println("Web Site Domain-Name : "+domain);
// To get all NodeList[1052] document.querySelectorAll('*'); or document.all
jse.executeAsyncScript("document.getElementsByTagName('*')");
String error=(String) jse.executeScript("return window.jsErrors");
System.out.println("Windowerrors : "+error);
System.out.println("To Find the input tag position from top");
ArrayList<?> al = (ArrayList<?>) jse.executeScript(
"var source = [];"+
"var inputs = document.getElementsByTagName('input');"+
"for(var i = 0; i < inputs.length; i++) { " +
" source[i] = inputs[i].offsetParent.offsetTop" + //" inputs[i].type = 'radio';"
"}"+
"return source"
);//inputs[i].offsetParent.offsetTop inputs[i].type
System.out.println("next");
System.out.println("array : "+al);
// (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys
Keys k = null;
String selectAll = Keys.chord(Keys.CONTROL, "a");
WebElement body = driver.findElement(By.tagName("body"));
body.sendKeys(selectAll);
// Search for text in Site. Gets all ViewSource content and checks their.
if (driver.getPageSource().contains("login")) {
System.out.println("Text present in Web Site");
}
Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
System.out.println("Client Body Height : "+clent_height);
// using selenium we con only execute script but not JS-functions.
}
driver.quit(); // to close browser
}
To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.
Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
String js_TxtFile = "";
while (sc.hasNext()) {
String[] s = sc.next().split("\r\n");
for (int i = 0; i < s.length; i++) {
js_TxtFile += s[i];
js_TxtFile += " ";
}
}
String title = (String) jse.executeScript(js_TxtFile);
System.out.println("Title : "+title);
document.title & document.getElementById() is a property/method available in Browsers.
JsFile.txt
var title = getTitle();
return title;
function getTitle() {
return document.title;
}
You can also try clicking by JavaScript:
WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);
Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.
I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here.
How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.
driver.executeScript("function(arguments[0]);","parameter to send in");
If you want to read text of any element using javascript executor, you can do something like following code:
WebElement ele = driver.findElement(By.xpath("//div[#class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);
In this example, I have following HTML fragment and I am reading "156".
<div class="infaCompositeViewTitle">
<span>All Assets</span>
<span>156</span>
</div>
Following code worked for me:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
public class SomeClass {
#Autowired
private WebDriver driver;
public void LogInSuperAdmin() {
((JavascriptExecutor) driver).executeScript("console.log('Test test');");
}
}
I had a similar situation and solved it like this:
WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
You need to run this command in the top-level directory of a Selenium SVN repository checkout.
I am just facing the issue at open new browser at "each click event previous opened stay that". i want that.
Look i want to open window browser at click event... it opens fine.
But i want at each click it opens new browser. how can i do that?
it always override that new window. i want always open a new window.
i used:
function Validation(){
var i=0;
if(document.netsim.emulatorNo.value=="")
{
alert ( "Please Fiil Emulator Number" );
netsim.emulatorNo.focus();
i=1;
}else {
var emu = document.netsim.emulatorNo.value;
var serverUrl = document.netsim.Apply.value;
window.open('http://localhost:8080/SMSSimulator/NewEmulator.jsp?emulator='+emu+'&ServerUrl='+serverUrl,'mywindow','width=400,height=350');
}
if(i==1)
return false;
}
suggest me to find out my answer.
Thanks in advance.
window.open(url, unique_title, features)
If you want to open it always on the new window use a unique window title everytime, else it will keep on opening on the same window.
Example sample html and popup opens fine in new window always -
<html>
<script>
var counter = 0;
function openWindow(){
window.open('http://www.google.com','mywindow'+counter,'width=400,height=350');
counter++;
}
</script>
<body>
<input type="button" value="button" id="button" onclick="openWindow()" />
</body>
</html>
you need to give different window names to each window. so, 'mywindow' needs to be changed. try something like;
var counter = 0;
function Validation(){
var i=0;
if(document.netsim.emulatorNo.value=="")
{
alert ( "Please Fiil Emulator Number" );
netsim.emulatorNo.focus();
i=1;
}else {
var emu = document.netsim.emulatorNo.value;
var serverUrl = document.netsim.Apply.value;
window.open('http://localhost:8080/SMSSimulator/NewEmulator.jsp?emulator='+emu+'&ServerUrl='+serverUrl,'mywindow'+counter,'width=400,height=350');
counter++;
}
if(i==1)
return false;
}
Here you open the new window in a specific place called 'mywindow'
window.open('http://localhost:8080/SMSSimulator/NewEmulator.jsp?emulator='+emu+'&ServerUrl='+serverUrl,'mywindow','width=400,height=350');
you can change it to blank or "_blank" and it will open it in a new window:
window.open('http://localhost:8080/SMSSimulator/NewEmulator.jsp?emulator='+emu+'&ServerUrl='+serverUrl,'','width=400,height=350');
there is no need to naming it unless you have a javascript that reference the window
If I have a simple button:
<ice:panelGroup>
<ice:commandButton value="foobar"
action="#{fileManager.openNoFlashVisiblePopup}" />
</ice:panelGroup>
Is it possible to trigger the action openNoFlashVisiblePopup using just javascript? I know that there IceFaces has a JavaScript bridge but I don't know see a simple way to do just this.
i need to do this because I have a chunk of JavaScript that detects Flash and I need to show a IceFaces popup.
One way is to get the button element by ID and call its click() function.
document.getElementById('clientId').click();
You only need to give the form and button a fixed id so that you can use the generated HTML ID as clientId in Javascript code.
I know I'm a little late in seeing this, but the correct way to handle this (minus perhaps the overly exhuberant error checking) is:
// There's a <div> that looks like: <div class="portletfaces-bridge-body" id="A8660">.
// We'll find it and pull out the value of the ID to build elementId like: A8660:wtfForm:editeventparent
var div = null;
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++) {
if(divCollection[i].getAttribute("class") == "portletfaces-bridge-body") {
div = divCollection[i];
break;
}
}
if (div == null){
alert("could not find div portletfaces-bridge-body.");
return;
}
// Pull the id out of divInnerText.
var id = div.getAttribute("id");
if (id == null){
alert("id was null");
}
// prepare initializes fields to null so rendered cannot begin until both itemId and parentId are set.
var prepare = document.getElementById(id + ":wtfForm:editeventprepare");
if (prepare == null){
alert("editeventprepare element was not found.");
return;
}
prepare.click();