I have been trying to login to faceboook and search a friend using Selenium. But I am stuck on this particular popup, and can't resolve this issue to proceed further.
public class FbAutomation {
public static void main(String[] args) {
FirefoxDriver browser = new FirefoxDriver();
browser.get("https://www.facebook.com/");
browser.manage().window().maximize();
browser.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
browser.findElement(By.xpath("//input[#name='email']")).sendKeys("user-email");
browser.findElement(By.xpath("//input[#name='pass']")).sendKeys("password");
/*Dimension radi = browser.findElement(By.xpath("//label[#id='loginbutton']")).getSize();
System.out.println("height is " + radi.height + " and width is " + radi.width);*/
browser.findElement(By.xpath("//label[#id='loginbutton']")).submit();
browser.navigate().to("https://www.facebook.com/imshaiknasir");
Alert alt = browser.switchTo().alert();
alt.accept();
/*
* Not able to handle "Allow notification" popUp box.
*/`enter code here`
browser.close();
}
}
Related
This is code I wrote :
public static void main(String args[]){
FirefoxProfile ffProfile = new FirefoxProfile();
FirefoxBinary ffBinary = new FirefoxBinary();
ffBinary.setTimeout(TimeUnit.SECONDS.toMillis(60));
ffProfile.setPreference("browser.download.dir","C:\\ComonFiles");
ffProfile.setPreference("browser.download.folderList", 2);
ffProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"
+ "application/pdf;"
+ "application/xml;"
+ "text/xml;"
+ "application/zip;"
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document;" + "text/plain;"
+ "text/csv");
System.setProperty("webdriver.gecko.driver","D:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver(ffBinary, ffProfile);
//Some other operations
downloadFile1();
downloadFile2();
}
public static void downloadFile1()
{
//Click on download button
}
public static void downloadFile2()
{
ffProfile.setPreference("browser.download.dir","C:\\WorkingFiles");
//Click on download button
}
I want to download File2 into some separate folder called C:\\WorkingFiles but it does not override download setting even if I am calling set preference again in downloadFile2(). It always download all files into C:\\ComonFiles. It still using preference of main function for download.
I tried using all known element identifier to select the tabs in the drag n drop options in the link but constantly giving error object cant be located .
can anyone help me.
public class DragnDrop {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "D:\\Auto\\geckodriver-v0.11.1-win32\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demoqa.com");
driver.findElement(By.xpath(".//*[#id='menu-item-140']/a")).click();
Actions builder = new Actions(driver);
WebElement know = driver.findElement(By.xpath(".//*[#id='tabs']/ul"));
builder.moveToElement(know, 10, 10 ).click().build().perform();
i tried to even use action to click at particular location none worked
As far as I can see, if it's the "Draggable + Sortable" tab you're trying to click, the below should allow that:
WebElement draggableTab = driver.findElement(By.id("ui-id-5"));
draggableTab.click();
I've tried the above (using C#) and it worked fine.
public class DragDrop {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver",
System.getProperty("user.dir") + "\\src\\Browser_Driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demoqa.com");
driver.findElement(By.xpath(".//*[#id='menu-item-140']/a")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(), 'Draggable + Sortable')]")));
driver.findElement(By.xpath("//a[contains(text(), 'Draggable + Sortable')]")).click();
// code works perfectly for demoqa site
Actions builder = new Actions(driver);
List<WebElement> list = driver.findElements(By.cssSelector("#sortablebox li"));
WebElement source = driver.findElement(By.id("draggablebox"));
WebElement dest1 = list.get(1);
WebElement dest2 = list.get(4);
builder.click(source).clickAndHold().moveToElement(dest1).moveByOffset(0, 10).release().build().perform();
Thread.sleep(2000);
builder.click(source).clickAndHold().moveToElement(dest2).moveByOffset(0, 10).release().build().perform();
So I had it working earlier but I messed up something in my code and now the FluentWait method doesnt seem to call properly. If I run it using quickRun set to false it works as intended (because of the implicit) but when I set it to true it doesnt as it will not wait for the elements to load correctly. Does anyone know exactly what I did wrong?
package myPackage;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import com.google.common.base.Function;
//import com.gargoylesoftware.htmlunit.javascript.host.Console;
//https://www.codeproject.com/articles/143430/test-your-web-application-s-ui-with-junit-and-sele
//this will open a dynamic page example (ie. youtube) trending
public class youtubeTest {
public boolean quickRun = false; //Disable for debugging otherwise full speed
private static int defaultDebugDelay = 2; //Time in sec for next test to occur in debug
//do no change any of the below
private String testUrl; //target url destination ie youtube
private WebDriver driver; //webdriver instance to reference within class
private int testIndex = 1; //initial index value for console outputting
public WebElement fluentWait(final By locator) {
Wait < WebDriver > wait = new FluentWait < WebDriver > (driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function < WebDriver, WebElement > () {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
});
return foo;
};
#
Before
public void beforeTest() {
driver = new SafariDriver();
System.out.println("Setting up Test...");
if (quickRun) {
System.out.println("Test Type: Quick Run (Fastest Mode)");
} else {
System.out.println("Test Type: Slow Run (Debug Mode) - Each Test has a " + defaultDebugDelay + " sec call time buffer");
}
testUrl = "https://www.youtube.com";
driver.get(testUrl);
System.out.println("Setting Driver " + driver + "for url: " + testUrl);
}
#
Test
public void Test() {
//insert unit tests within here
//open yt nav menu
locateClickableElement("#appbar-guide-button");
//go to trending
locateClickableElement("#trending-guide-item");
//click on 4th Trending video from list
//locateClickableElement(".expanded-shelf-content-item-wrapper", 3);
locateClickableElement(".expanded-shelf-content-item-wrapper");
}
#
After
public void afterTest() throws Exception {
//wait 10 sec before closing test indefinitely
System.out.println("Test auto ending in 10 seconds...");
Thread.sleep(10000);
stopTest();
}
//individual unit tests
private void locateClickableElement(String ExpectedElement, int child) {
//format string into something like: "ELEMENT:nth-child(1)"
String formattedString = ExpectedElement + ":nth-child(" + child + ")";
System.out.println("Strung: " + formattedString);
locateClickableElement(formattedString);
}
private void locateClickableElement(String ExpectedElement) {
try {
System.out.println("Test " + testIndex + ": locateClickableElement(" + ExpectedElement + ")");
//do absolute delay for visual debugging
if (!quickRun) Thread.sleep(2000);
//click on target if found
fluentWait(By.cssSelector(ExpectedElement)).click();
System.out.println("Test " + testIndex + ": Successful Click on Element(" + ExpectedElement + ")");
} catch (Exception e) {
//whenever error is found output it and end program
System.out.println("Error Could not locateClickableElement(" + ExpectedElement + ")");
System.out.println("Exception Handled:" + e.getMessage());
stopTest("error");
}
testIndex++;
}
private void stopTest() {
System.out.println("Test Completed: Reached End.");
driver.quit();
}
private void stopTest(String typeError) {
System.out.println("Test Completed: With an Error.");
driver.quit();
}
}
I would write this a different way and offer some advice.
Don't slow your test down using "debug mode". If you want to debug your test, use breakpoints and step through the code to see how it's working.
You don't need FluentWait here. A simple WebDriverWait using ExpectedConditions.elementToBeClickable(locator) will work just fine and is less complicated. You shouldn't even need it, if you accept my changes.
Don't pass locators using String, use the intended locator class, By. You won't have to interpret it, translate it, etc. and it will be faster and more flexible.
Unless you are trying to test the UI (which I'm assuming you don't work for youtube), then you can just navigate to the Trending page using the Trending link at the top of the page. It will save you time and clicks. If you aren't testing it, don't test it... get to where you are going as fast as possible. You don't want your test failing due to UI you aren't trying to test and you always want your tests to go as fast as possible. (NOTE: You could even navigate directly to the trending URL.)
You don't need the locateClickableElement() functions. Just click the links... it should be a one liner. If there's an error, it will be obvious. You don't need to print, "There was an error." after an exception message was printed.
You don't need the stopTest() functions... just stop the test. When the browser closes, it will be obvious the test is complete.
The rewritten code is below. It's nice and simple (and short) and should be faster.
public class youtubeTest
{
// do no change any of the below
private String testUrl = "https://www.youtube.com"; // target url destination ie youtube
private WebDriver driver; // webdriver instance to reference within class
private By trendingGuideLinkLocator = By.cssSelector("#trending-guide-item");
private By trendingLinkLocator = By.xpath("//h2[contains(.,'Trending')]");
#Before
public void beforeTest()
{
System.out.println("Setting up Test..."); // if you are going to have this statement, put it at the start of beforeTest()
driver = new SafariDriver();
driver.get(testUrl);
System.out.println("Set Driver " + driver + "for url: " + testUrl);
}
#Test
public void Test()
{
// insert unit tests within here
driver.findElement(trendingLinkLocator).click(); // just click the Trending link, it's faster
driver.findElements(trendingGuideLinkLocator).get(3).click();
}
#After
public void afterTest()
{
driver.close();
driver.quit();
}
}
If you don't want to change all this, the simple answer to your question is replace FluentWait with WebDriverWait.
fluentWait(By.cssSelector(ExpectedElement)).click();
would be replaced by
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(trendingLinkLocator)).click();
Actually, i'm trying to switch the control from current window to existing window after closing the current one in Selenium Automation using java. Is there any way to do that. I'm able to control the newly opened window, doing some process & closing this one. Later i just need to move to already existing browser window.
This is something that I use , this checks for all the open windows and then switchess control to the next window with an option to close out the older window.
protected final void switchWindows(boolean closeOldWindow) {
final WebDriver driver = checkNotNull(getDriver(), "missing WebDriver");
final String currentWindow = driver.getWindowHandle();
checkNotNull(currentWindow);
// switch to first window that is not equal to the current window
String newWindow = null;
for (final String handle : driver.getWindowHandles()) {
if (!currentWindow.equals(handle)) {
newWindow = handle;
break;
}
}
// if there's another window found...
if (newWindow != null) {
if (closeOldWindow) {
// close the current window
driver.close();
}
// ...switch to the new window
driver.switchTo().window(newWindow);
}
}
I just know selenium js webdriver have a api like driver.switchTo().window(windowName) could help us move to another window. I am not so familiar with Java API but they are all from almost same invoking way. hope this would help you.
you can use this-
private void handleMultipleWindows(String windowTitle) {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().contains(windowTitle)) {
return;
}
}
}
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows
Once you closed the current window, you will be seeing the parent window.
To switch back to your parent/previous window you can use the following commands,
driver.getUIWindowLocator().switchToFirstWindow();
driver.switchTo().defaultContent();
commands. I think this will be helpful for you.
Please do following code for switching back to base window or original window.
String vBaseWindowHandle = driver.getWindowHandle();
Set<String> windows = driver.getWindowHandles();
for(String temp : windows)
{
driver.switchTo().window(temp);
}
// Do code for new window
driver.close();
driver.switchTo().window(vBaseWindowHandle);
For more information about how to handle Windows and popup in selenium please go to below URL.
https://trickyautomationworld.blogspot.in/2018/03/how-to-handle-windows-in-selenium.html
https://trickyautomationworld.blogspot.in/2018/03/how-to-handle-popup-in-selenium.html
This is my code that opens a webpage and feeds input text into textfield and tries to browse further automatically. The first code: element.sendKeys(Keys.ENTER); is working but the next two lines immediately after this have no effect in my program. I am stuck here. Pls help me
public class GoogleSuggest {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("vtu results");
element.sendKeys(Keys.ENTER);
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.Enter);
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("v");
}
});
System.out.println("Page title is: " + driver.getTitle());
}
}
Not clear what all actions you want perform but following working for me.
Try this out:
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
Actions action = new Actions(driver);
element.sendKeys("result");
action.sendKeys(element,Keys.ENTER).perform();
action.sendKeys(Keys.TAB);
Thread.sleep(2000);
action.sendKeys(Keys.ENTER).perform();
Thread.sleep(2000);
System.out.println("Page title is: " + driver.getTitle());
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("R");
}
});
System.out.println("Page title is: " + driver.getTitle());
}