How to click an element in Selenium WebDriver using JavaScript? - java

I have the following HTML:
<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>
My following code for clicking "Google Search" button is working well using Java in WebDriver.
driver.findElement(By.id("gbqfb")).click();
I want to use JavaScript with WebDriver to click the button. How can I do it?

Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.
// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

Here is the code using JavaScript to click the button in WebDriver:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('gbqfb').click();");

I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:
public static void mouseClickByLocator( String cssLocator ) {
String locator = cssLocator;
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}

Not sure OP answer was really answered.
var driver = new webdriver.Builder().usingServer('serverAddress').withCapabilities({'browserName': 'firefox'}).build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.id('gbqfb')).click();

You can't use WebDriver to do it in JavaScript, as WebDriver is a Java tool. However, you can execute JavaScript from Java using WebDriver, and you could call some JavaScript code that clicks a particular button.
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('gbqfb').click()");

By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);

const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !

This code will perform the click operation on the WebElement "we" after 100 ms:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", we);

Another easiest solution is to use Key.RETUEN
Click here for solution in detail
driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);

I think some parts of above codes has changed a little, I'm learning Selenium with JavaScript and I founded 2 options to click
To start we need to find the element we want to click, could be By (id, class, etc.), here is how, https://www.youtube.com/watch?v=BQ-9e13kJ58&list=PLZMWkkQEwOPl0udc9Dap2NbEAkwkdOTV3.
Right down are the 2 ways that I'm talking about:
FIRST Method:
await driver.findElement(By.id("sampletodotext")).sendKeys("Learning Selenium", Key.RETURN);
- Here we found an empty field by it's Id, and then we write "Learning Selenium" in this field with the sendKeys().
- Key.RETURN: Simulate the person pressing the ENTER key in keyboard.
SECOND Method:
await driver.findElement(By.id("sampletodotext")).sendKeys("Learn Selenium");
await driver.findElement(By.id("addbutton")).click().finally();
- The difference here, is we switched the Key.RETURN of the FIRST method, for the entire second line, in the SECOND method.

Use the code below, which worked for me:
public void sendKeysJavascript() {
String file = getfile();
WebElement browser = driver.findElement(By.xpath("//input[#type='file']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
actionClass.waitforSeconds(5);
js.executeScript("arguments[0].click();", browser);
actionClass.waitforSeconds(1);
browser.sendKeys(file);
}
String getfile() {
return new File("./src/main/resources/TestData/example.pdf").getAbsolutePath();
}
Don't forget to add wait time before the js click action. It is mandatory

Cross browser testing java scripts
public class MultipleBrowser {
public WebDriver driver= null;
String browser="mozilla";
String url="https://www.omnicard.com";
#BeforeMethod
public void LaunchBrowser() {
if(browser.equalsIgnoreCase("mozilla"))
driver= new FirefoxDriver();
else if(browser.equalsIgnoreCase("safari"))
driver= new SafariDriver();
else if(browser.equalsIgnoreCase("chrome"))
//System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.navigate().to(url);
}
}
but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .

Related

How to click on the button as per the HTML provided?

This is the html code for the button in the pop up ( pop up has a lead gen form) -
<button id="getCoupon" class="fetch" data-bind="click: submitForm" type="submit">Fetch Coupon</button>
This is the script which I have written in JAVA in Eclipse. I am able to fill the name, Email and Phone number but I'm not able to click on the button -
driver.findElement(By.id("getCoupon")).click();
As per the comment and URL, you have shared :
You can try with this code :
public class Pawan {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user**\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://vets.cm.qa.preview.vca.webstagesite.com/free-first-exam");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[value='/santa-monica']~div.select-btn"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("fName"))).sendKeys("Pawan");
wait.until(ExpectedConditions.elementToBeClickable(By.id("lName"))).sendKeys("Sharma");
wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("ps12#gmail.com");
wait.until(ExpectedConditions.elementToBeClickable(By.id("zip"))).sendKeys("90404");
wait.until(ExpectedConditions.elementToBeClickable(By.id("phone"))).sendKeys("9697989900");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,100)", "");
wait.until(ExpectedConditions.elementToBeClickable(By.id("getCoupon"))).click();
}
}
As per your HTML code, your id is : "getCoupon",
whereas in code you mentioned id as : "getCouponFetch". Please correct and it should work. Code -
driver.findElement(By.id("getCoupon")).click();
If selenium click don't work, use below Java Script click code :
WebElement element = driver.findElement(By.id("getCoupon")); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", element);
Firstly, what kind of error did you get??
Try using implicit wait if your getting "NoSuchElementException" like below:
driver.manage().timeOuts().implicitlywait(30,TimeUnit.SECONDS);
Then try using the below way to locate that button:
driver.findElementByXpath("text()[contains(.,'Fetch Coupon')]").click();
As per the HTML you have shared to click() on the button you have to induce WebDriverWait for the desired element to be clickable and you can use either of the following solutions:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.fetch#getCoupon"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='fetch' and #id='getCoupon'][contains(.,'Fetch Coupon')]"))).click();
Update
As an alternative you can use the executeScript() method to invoke the click() as follows:
Using cssSelector:
WebElement fetch_coupon = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.fetch#getCoupon")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", fetch_coupon);
Using xpath:
WebElement fetch_coupon = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='fetch' and #id='getCoupon'][contains(.,'Fetch Coupon')]")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", fetch_coupon);

Do we have any generic function to check if page has completely loaded in Selenium

I am trying to check if web page is loaded completed or not (i.e. checking that all the control is loaded) in selenium.
I tried below code:
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
but even if page is loading above code does not wait.
I know that I can check for particular element to check if its visible/clickable etc but I am looking for some generic solution
As you mentioned if there is any generic function to check if the page has completely loaded through Selenium the answer is No.
First let us have a look at your code trial which is as follows :
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
The parameter pageLoadTimeout in the above line of code doesn't really reseambles to actual pageLoadTimeout().
Here you can find a detailed discussion of pageLoadTimeout in Selenium not working
Now as your usecase relates to page being completely loaded you can use the pageLoadStrategy() set to normal [ the supported values being none, eager or normal ] using either through an instance of DesiredCapabilities Class or ChromeOptions Class as follows :
Using DesiredCapabilities Class :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class myDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
DesiredCapabilities dcap = new DesiredCapabilities();
dcap.setCapability("pageLoadStrategy", "normal");
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dcap);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
System.out.println(driver.getTitle());
driver.quit();
}
}
Using ChromeOptions Class :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.PageLoadStrategy;
public class myDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
FirefoxOptions opt = new FirefoxOptions();
opt.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
System.out.println(driver.getTitle());
driver.quit();
}
}
You can find a detailed discussion in Page load strategy for Chrome driver (Updated till Selenium v3.12.0)
Now setting PageLoadStrategy to NORMAL and your code trial both ensures that the Browser Client have (i.e. the Web Browser) have attained 'document.readyState' equal to "complete". Once this condition is fulfilled Selenium performs the next line of code.
You can find a detailed discussion in Selenium IE WebDriver only works while debugging
But the Browser Client attaining 'document.readyState' equal to "complete" still doesn't guarantees that all the JavaScript and Ajax Calls have completed.
To wait for the all the JavaScript and Ajax Calls to complete you can write a function as follows :
public void WaitForAjax2Complete() throws InterruptedException
{
while (true)
{
if ((Boolean) ((JavascriptExecutor)driver).executeScript("return jQuery.active == 0")){
break;
}
Thread.sleep(100);
}
}
You can find a detailed discussion in Wait for ajax request to complete - selenium webdriver
Now, the above two approaches through PageLoadStrategy and "return jQuery.active == 0" looks to be waiting for indefinite events. So for a definite wait you can induce WebDriverWait inconjunction with ExpectedConditions set to titleContains() method which will ensure that the Page Title (i.e. the Web Page) is visible and assume the all the elements are also visible as follows :
driver.get("https://www.google.com/");
new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("partial_title_of_application_under_test"));
System.out.println(driver.getTitle());
driver.quit();
Now, at times it is possible though the Page Title will match your Application Title still the desired element you want to interact haven't completed loading. So a more granular approach would be to induce WebDriverWait inconjunction with ExpectedConditions set to visibilityOfElementLocated() method which will make your program wait for the desired element to be visible as follows :
driver.get("https://www.google.com/");
WebElement ele = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_of_the_desired_element")));
System.out.println(ele.getText());
driver.quit();
References
You can find a couple of relevant detailed discussions in:
Selenium IE WebDriver only works while debugging
Selenium how to manage wait for page load?
I use selenium too and I had the same problem, to fix that I just wait also for the jQuery to load.
So if you have the same issue try this also
((Long) ((JavascriptExecutor) browser).executeScript("return jQuery.active") == 0);
You can wrap both function in a method and check until both page and jQuery is loaded
Implement this, Its working for many of us including me. It includes Web Page wait on JavaScript, Angular, JQuery if its there.
If your Application is containing Javascript & JQuery you can write code for only those,
By define it in single method and you can Call it anywhere:
// Wait for jQuery to load
{
ExpectedCondition<Boolean> jQueryLoad = driver -> ((Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active") == 0);
boolean jqueryReady = (Boolean) js.executeScript("return jQuery.active==0");
if (!jqueryReady) {
// System.out.println("JQuery is NOT Ready!");
wait.until(jQueryLoad);
}
wait.until(jQueryLoad);
}
// Wait for ANGULAR to load
{
String angularReadyScript = "return angular.element(document).injector().get('$http').pendingRequests.length === 0";
ExpectedCondition<Boolean> angularLoad = driver -> Boolean.valueOf(((JavascriptExecutor) driver).executeScript(angularReadyScript).toString());
boolean angularReady = Boolean.valueOf(js.executeScript(angularReadyScript).toString());
if (!angularReady) {
// System.out.println("ANGULAR is NOT Ready!");
wait.until(angularLoad);
}
}
// Wait for Javascript to load
{
ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString()
.equals("complete");
boolean jsReady = (Boolean) js.executeScript("return document.readyState").toString().equals("complete");
// Wait Javascript until it is Ready!
if (!jsReady) {
// System.out.println("JS in NOT Ready!");
wait.until(jsLoad);
}
}
Click here for Reference Link
Let me know if you stuck anywhere by implementing.
It overcomes the use of Thread or Explicit Wait.
public static void waitForPageToLoad(long timeOutInSeconds) {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
try {
System.out.println("Waiting for page to load...");
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeOutInSeconds);
wait.until(expectation);
} catch (Throwable error) {
System.out.println(
"Timeout waiting for Page Load Request to complete after " + timeOutInSeconds + " seconds");
}
}
Try this method
This works for me well with dynamically rendered websites:
Wait for complete page to load
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
Make another implicit wait with a dummy condition which would always fail
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + "This text will always fail :)" + "')]"))); // condition you are certain won't be true
}
catch (TimeoutException te) {
}
Finally, instead of getting the html source - which would in most of one page applications would give you a different result , pull the outerhtml of the first html tag
String script = "return document.getElementsByTagName(\"html\")[0].outerHTML;";
content = ((JavascriptExecutor) driver).executeScript(script).toString();
There is a easy way to do it. When you first request the state via javascript, it tells you that the page is complete, but after that it enters the state loading. The first complete state was the initial page!
So my proposal is to check for a complete state after a loading state. Check this code in PHP, easily translatable to another language.
$prevStatus = '';
$checkStatus = function ($driver) use (&$prevStatus){
$status = $driver->executeScript("return document.readyState");
if ($prevStatus=='' && $status=='loading'){
//save the previous status and continue waiting
$prevStatus = $status;
return false;
}
if ($prevStatus=='loading' && $status=='complete'){
//loading -> complete, stop waiting, it is finish!
return true;
}
//continue waiting
return false;
};
$this->driver->wait(20, 150)->until($checkStatus);
Checking for a element to be present also works well, but you need to make sure that this element is only present in the destination page.
Something like this should work (please excuse the python in a java answer):
idle = driver.execute_async_script("""
window.requestIdleCallback(() => {
arguments[0](true)
})
""")
This should block until the event loop is idle which means all assets should be loaded.

Selenium in Java Error: Missing or invalid type argument for pointer action

I am getting this error "Missing or invalid type argument for pointer action" while trying to execute the below code for Selenium in Java.
public static void main(String args[]) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get("https://www.flipkart.com/");
driver.findElement(By.xpath(".//*[#class='_3Ji-EC']/li[8]/a")).click();
WebElement elem = driver.findElement(By.className("_2zrpKA"));
elem.sendKeys("ABC");
WebElement elem2 = driver.findElement(By.xpath(".//*[#class='_2zrpKA
_3v41xv']"));
elem2.sendKeys("XYZ");
driver.findElement(By.xpath(".//*[#class='_2AkmmA _1LctnI
_7UHT_c']")).click();
System.out.println("Success");
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(5000);
WebElement elem3 = driver.findElement(By.xpath(".//*[#class='_3Ji-
EC']/li[7]/a"));
System.out.println("success");
Actions action = new Actions(driver);
action.moveToElement(elem3).build().perform();
driver.findElement(By.xpath(".//*[#class='_1u5ANM']/li[9]/a")).click();
}
I have tried this using Selenium 3.4.0 and Firefox 51.x, 52.x, 53.x with the latest geckodriver 16.1 and 16.0 .
When I used Firefox 53.x, I was getting the error "Expected [object Undefined] undefined to be a string" else every time I am getting the error "Missing or invalid type argument for pointer action".
In the above code I am able to get "success" printed 2nd time without any problem but after that I am getting the error.
Here is the solution to your Question:
To work with Selenium 3.4.0 with geckodriver v0.16.1 & Mozilla Firefox 53.x you need to specify the absolute path of the geckodriver in your code as:
System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
Your xpath seems petty vulnerable to me. You may want to construct more unique logical xpath. To click on Log In button you may do:
driver.findElement(By.xpath("//div[#class='AsXM8z']/ul/li/a[#class='_2k0gmP'][text()='Log In']")).click();
I would suggest you not to rely only on class, append some more properties. The xpath for Enter Email field can be:
WebElement elem = driver.findElement(By.xpath("//input[#class='_2zrpKA']"));
The xpath for Enter Password is not unique, you may like to change it to:
WebElement elem2 = driver.findElement(By.xpath("//input[#class='_2zrpKA _3v41xv']"));
The xpath for the Login button needs to be unique as follows:
driver.findElement(By.xpath("//button[#class='_2AkmmA _1LctnI _7UHT_c']")).click();
Avoid using Thread.sleep(5000); rather use ImplicitlyWait or ExplicitWait
The xpath to click on the Username is again vulnerable, you may like to change it to:
WebElement elem3 = driver.findElement(By.xpath("//div[#class='AsXM8z']/ul/li/a[#class='_1AHrFc _2k0gmP']"));
The xpath to click the Log Out button is again vulnerable, you may like to change it to:
driver.findElement(By.xpath("//div[#class='_1H5F__']/div/ul/li/ul/li/a[#class='_2k0gmP'][text()='Log Out']")).click();
Here is your own working code block with some simple tweaks;
System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.flipkart.com/");
driver.findElement(By.xpath("//div[#class='AsXM8z']/ul/li/a[#class='_2k0gmP'][text()='Log In']")).click();
//Email
WebElement elem = driver.findElement(By.xpath("//input[#class='_2zrpKA']"));
elem.sendKeys("emailid#domain.com");
//Password
WebElement elem2 = driver.findElement(By.xpath("//input[#class='_2zrpKA _3v41xv']"));
elem2.sendKeys("pass_word");
//Login Button
driver.findElement(By.xpath("//button[#class='_2AkmmA _1LctnI _7UHT_c']")).click();
System.out.println("Success");
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(5000);
//Click on Name
WebElement elem3 = driver.findElement(By.xpath("//div[#class='AsXM8z']/ul/li/a[#class='_1AHrFc _2k0gmP']"));
System.out.println("success");
Actions action = new Actions(driver);
action.moveToElement(elem3).build().perform();
driver.findElement(By.xpath("//div[#class='_1H5F__']/div/ul/li/ul/li/a[#class='_2k0gmP'][text()='Log Out']")).click();
Let me know if this Answers your Question.

How to return WebElement having particular CSS property using JavascriptExecutor?

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");

How to scroll down using Selenium WebDriver with Java

I want to scroll down my web page and i m using this code to scroll page but it is not working
public ViewBasketSentToMePageObject viewSlideShare() throws InterruptedException {
Thread.sleep(500l);
Actions action1 =new Actions(getDriver());
action1.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0030')).build().perform();
List<WebElement> function = getDriver().findElements(By.xpath("//a [#ng-click='onItemClick()']"));
function.get(13).findElement(By.xpath("//img [#ng-src='resources/images/slideshare-icon-small.png']")).click();
return getFactory().create(ViewBasketSentToMePageObject.class);
}
Looking for help
Try using simple java script below and you can scroll the page.
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("window.scrollBy(0,450)", "");
For scroll down:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 250);");
or, you can do as follows:
jse.executeScript("window.scrollBy(0,250)", "");
Scroll until find the WebElement
Try this:
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", your_WebElement);
WebElement element = driver.findElement(By.xpath("//input [#id='giveid']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element);
Use this. This will help you to scroll down at the particular element. I had tested on my website even. It is working fine.

Categories

Resources