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! :)
Related
I have a html page:
<video crossorigin="anonymous" class="" id="video" playsinline="true"
src="https://df.dfs.bnt.com/
DEEAB832j06E9j413FjAA8Dj2zxc535DA2072E3jW01j15579/mp4-
hi/jFNf2IbBoGF28IzyU_WqkA,1535144598/zxxx/
contents/1/8/1a57ae021173751b468cca136e0192.mp4?
rnd=0.38664488150364296">
</video>
Through Selenium WebDriver I tried get video url:
By videoLocator = By.id("video");
WebElement videoElement = driver.findElement(videoLocator);
String videoUrl = videoElement.getAttribute("src");
But videoUrl - always returns ""(is empty).
Š¯owever for example:
videoElement.getAttribute("crossorigin")
return correct answer: "anonymous".
I have tried get this url from src attribute using javascript:
String videoUrl = (String) js.executeScript("return document.getElementById( 'video' ).getAttribute( 'src' );");
But the result is still the same: "".
I guess that the problem is in crossorigin="anonymous" but what to do with it? How can I get src value?
Sorry, for my poor English.
As per the HTML you have provided you need to induce WebDriverWait and you can use the following solution:
WebElement videoElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//video[#id='video' and #crossorigin='anonymous'][starts-with(#src,'http')]")));
System.out.println(videoElement.getAttribute("src"));
Try fetching innerHTML attribute. Code :
By videoLocator = By.id("video");
WebElement videoElement = driver.findElement(videoLocator);
String videoUrl = videoElement.getAttribute("innerHTML");
I want to read WebPageId in following script by using java.
Could you please help me out.
Function:
jQuery(document).ready(function() {
try{_paq.push(["setSid", 8]);
_paq.push(["setSid","environment"]);
(function () {
var configarray = ['www.xyz.com'];
if (configarray.indexOf(window.location.hostname)!=-1)
{_paq.push(['setCVariable','1','webPageId',12345,'page']);
_paq.push(["trackPageView"]);}
You need to set a variable to a javascript that returns using this syntax:
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
} // else throw...
// later on...
js.executeScript("return document.getElementById('someId');");
I am working on a scenario where I need to find a WebElement based on its CSS property, like background-color.
I have created the JQuery to find the element as below and it finds the webelement correctly using firefox console.
$('.search-bar-submit').each(function() {
return $(this).css('background-color') == '#fdd922';
});
Hence, I wrote the code to find this WebElement, i.e. searchbox and then tried to click it.
driver.get("http://www.flipkart.com/");
driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");
String query ="$('.search-bar-submit').each(function() { "
+ "return $(this).css('background-color') == '#fdd922'; });";
WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);
searchbox.click();
When I run the program, it gives me Exception in thread "main" java.lang.NullPointerException on line searchbox.click();
Can anyone help me out find the searchbox using JavascriptExecutor and then click on it? Am I missing something silly here?
Any help is appreciated. Thanks in Advance.
WebElement searchbox = (WebElement)
((JavascriptExecutor)driver).executeScript(query);
The above code calls the function but doesn't do anything with the result, ie. it doesn't return it to the caller.
Add return in the script to return the webelement to the selenium script(webdriver)
return $('.search-bar-submit').each(function() {
return $(this).css('background-color') == '#fdd922';
});
The return type is List<WebElement>so typecast it to List if you typecast it to it will throw an ClassCastException as arraylist cannot be cast to a webelement
Code:
List<WebElement> searchbox = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(query);
for(int i=0;i<searchbox.size();i++){
searchbox.get(i).click();
}
EDIT:
The code was not working in firefox because the firefox browser returns a json object of the webelement.Selenium replaced its uses of org.json with gson.So it is not able to understand the response recieved
Screenshot taken from chrome
Screenshot taken from firefox
Solution
We are using Jquery get function to retrieve the DOM Elements matched by the jquery object
$('.search-bar-submit').each(function() {
return $(this).css('background-color') == '#fdd922';
}).get(0);
Code
public class jquerytest
{
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.flipkart.com");
driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");
String query ="return $('.search-bar-submit').each(function() { "
+ "return $(this).css('background-color') == '#fdd922'; }).get(0);";
Thread.sleep(5000);//wait till page loads replace thread.sleep by any waits
WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);
searchbox.click();
}
}
I have tested the above code on both chrome and firefox it works perfectly
Hope this helps you.Kindly get back if you have any queries
I ran the following code and it all works fine. Your jquery works as well (I love the little message they print to console in the dev view hahaha).
driver.get("http://www.flipkart.com/");
WebElement in = driver.findElement(By.id("fk-top-search-box"));
in.sendKeys("iphone");
WebElement thing = driver.findElement(By.className("fk-font-bold"));
thing.click();
I believe there's a problem with your executeScript and it should be as follows.
System.out.println(((JavascriptExecutor)driver).executeScript(query, driver));
Normally the format for my calling javascript is as follows, this would be to remove the windowed attribute so that a hyperlink would open in the same tab:
String Href = linkObject.getAttribute("href");//located the hyperlink for the documents
Href = Href.substring(0, Href.length()-10)+")";//I remove ",'windowed'" from the link to stop it opening in a new window and having to change the scripts focus
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return arguments[0].href = \""+Href + "\"", linkObject););
But then you're getting JSON back and WebDriver can't understand that. See the following link for more information on that.
http://grokbase.com/t/gg/webdriver/12ckjcthg8/executing-javascript-that-returns-json-how-best-to-handle
Might I suggest this alternative, it gives the background-color in rgba format:
WebElement pain = driver.findElement(By.className("search-bar-submit");
pain.getCssValue("background-color");
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'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();