The app is going to load the system default browser, load a special website, and then login automatically
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class theurl {
public static void main(String[] args) {
String url = "http://www.playok.com/en/spades/";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
But before trying to login, first the cookies should be accepted automatically; is there a simple way to do it rather than using an external library? if not, which library can do the job
I tried this code, but didnt help:
WebDriver Driver = new ChromeDriver();
Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String url = "http://www.playok.com/en/spades/";
Driver.get(url);
Driver.findElement(By.id("cookie_action_close_header")).click();
System.out.println("completed");
To click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:
cssSelector:
Driver.get("http://www.playok.com/en/spades/");
new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.ckbut.but0"))).click();
xpath:
Driver.get("http://www.playok.com/en/spades/");
new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='ckbut but0' and text()='ACCEPT']"))).click();
Related
I am trying to drag and drop using Selenium Java. It is clicking but not dropping it in the destination specified.
Code used for dragging and dropping:
WebElement drag= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[1]/div/vr-columns/div/vr-toolbox/div/div[3]"));
//Drop
WebElement Drop= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[2]/div/vr-columns/div/div[2]/div/vr-validator/div/div[1]/vr-datagrid/vr-datagridrows/div[1]/div/div[2]/div[1]"));
Actions actions= new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
If this is not working, please share URL or page source code.
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
public class DragAndDropTest extends WebDriverSetup {
public static void main (String[] args) {
WebDriver driver = startChromeDriver(); // standard driver setup just wrapped
driver.get("https://demoqa.com/droppable/");
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(draggable, droppable).build().perform();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
driver.quit();
}
}
First, you have to move to the element you want to drag. Besides, you can use chaining.
...(your codes are above)
actions.moveToElement(drag)
.clickAndHold()
.moveToElement(Drop)
.release(Drop).perform();
try {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(drag));
Actions actions = new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
} catch (Exception e) {
System.out.println("Error occurred while dragging and dropping: " + e.getMessage());
}
While taking screenshot in selenium, if I use the dot(.) operator to mention the destination folder path instead of the full path, then the code is returning the error :
java.io.FileNotFoundException: .\Screenshot\shot1.jpeg
(The system cannot find the path specified)
I am using the dot operator for the folder variable. As per my understanding the dot means, it represents the project folder. However, if I use the actual path "F:/SeleniumRevisit/Screenshot/shot1.jpeg", the code is working without any problem. My project folder is SeleniumRevisit which is present in F: drive. Any help would be appreciated.
Code :
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.io.FileHandler;
public class Screenshot_getScreenshotAs
{
public static void main(String[] args) throws InterruptedException, IOException
{
String key="webdriver.chrome.driver";
String value="./Drivers/chromedriver.exe";
System.setProperty(key,value);
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/test/simple_context_menu.html");
Thread.sleep(2000);
TakesScreenshot ts=(TakesScreenshot) driver;
File src=ts.getScreenshotAs(OutputType.FILE);
File dst=new File("./Screenshot/shot1.jpeg");
FileHandler.copy(src,dst);
}
}
//For capture screenshot and save the destination please use this code.
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//BY try catch block.
try {
FileUtils.copyFile(screenshot, new
File("C:\\projectScreenshots\\homePageScreenshot.png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
You can try with user.dir give the folder and screenshot name
public static void fullPageScreenShot() {
String screens = System.getProperty("user.dir") +
"./Screenshot/shot1.jpeg";
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileHandler.copy(screenshot, new File(screens));
} catch (IOException e) {
System.out.println(e.getMessage());
}
//closing the webdriver
driver.close();
}
I've written a code using Selenium WD and JUnit that should check if proper page is loaded and the table of this page is not null
Besides assertion, to make sure that proper page is loaded (checking if URL contains specified text), I've put "if-else" statement in "waitUntilPageLoaded" method.
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GuruSearch
{
#Test
static void checkDemoLogin()
{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pansa\\Documents\\Webdrivers\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 10);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(FirefoxDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The "if-else" statement in "waitUntilPageLoaded" method returns "OK", but TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"))
throws AssertionError, although the text appears in the page.
Why there is AssertionError thrown?
As you are using the JUnit annotations, the annotated method shouldn't be static. I have modified your code a bit, try the below:
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.TestCase;
public class GuruSearch
{
#Test
public void checkDemoLogin()
{
System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 30);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(WebDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The above code is printing 'OK' and Assert condition also passing. And I think, it doesn't matter if we give upper/lower case in the contains. It will match both the cases.
I don't have Firefox in my system so I have checked with Chrome, you change the browser and try... I hope it helps...
I want to export the cookies along with headers to file after a successful login in Selenium, I am able to login using Selenium.
Below is my code which does login in to a website using Selenium
package login;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.Logs;
public class Login1 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:/Program Files (x86)/Google/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("url");
driver.manage().window().maximize();
driver.findElement(By.id("username")).sendKeys("namehere");
driver.findElement(By.id("password")).sendKeys("passhere");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.id("submit")).click();
Logs logs = driver.manage().logs();
LogEntries logEntries = logs.get(LogType.DRIVER);
for (LogEntry logEntry : logEntries) {
System.out.println(logEntry.getMessage());
}
}
}
This is an example with Selenium to save all the cookies to a file:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Path cookiesFile = Paths.get("C:\\Temp\\cookies.txt");
// save the cookies to a file for the current domain
try (PrintWriter file = new PrintWriter(cookiesFile.toFile(), "UTF-8")) {
for (Cookie c : driver.manage().getCookies()) {
file.println(c.toString());
}
}
As for the headers, well Selenium doesn't provide an API to get them.
driver.get("https://www.facebook.com/sachin.aryal");
driver.findElement(By.name("xhpc_message_text")).sendKeys("Testing Java and Selenium");
driver.findElement(By.xpath("//*[#id='u_0_1a']/div/div[6]/div/ul/li[2]/button")).click();
The last line of the code is not working. How do I set the XPath of the Post button on facebook?
I know you already marked your own answer but it's not the proper way to do this. There are ways built into Selenium to do waits, e.g. wait for an element to be clickable. This method is the proper and more efficient way to do this.
driver.get("https://www.facebook.com/sachin-aryal/");
driver.findElement(By.name("xhpc_message_text")).sendKeys("Testing Java and Selenium");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button/span[.=\"Post\"]"))).click();
I noticed it works when you first scroll into view the button, try adding before the click on post the:
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,259)","");
Try the below code .. it must work for you..
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Facebook_login {
public static void main(String[] args) throws InterruptedException {
String user_name = "facebook_user_name";
String pwd = "facebook_password";
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys(user_name);
driver.findElement(By.name("pass")).clear();
driver.findElement(By.name("pass")).sendKeys(pwd);
driver.findElement(By.xpath("//input[contains(#value,'Log In')]")).click();
Thread.sleep(10000);
System.out.println("logged in successfully");
WebElement notification = driver.findElement(By.xpath("//a[contains(#action,'cancel')]"));
if(notification.isDisplayed()) {
System.out.println("Notification is present");
notification.click();
}
WebElement status =driver.findElement(By.xpath("//textarea[#name='xhpc_message']"));
status.sendKeys("Hello");
Thread.sleep(3000);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Post']"))).click();
}
}