PhantomJSDriver: Not able to switch to newly opened browser window - java

I have been trying to use PhantomJSWebDriver framework for automating an application using Headless browser. The main issue is as we can successfully switch between windows in firefox or IE windows, here I am not able to switch between windows based on handles. Please help me.
Below is the code I have tried so far.
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
driver = new PhantomJSDriver();
driver.get(application url);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
WebElement txtUsername = driver.findElement(By.id("it_C_C5"));
txtUsername.sendKeys("sreenis");
WebElement txtPassword = driver.findElement(By.id("it_C_C7"));
txtPassword.sendKeys("sreeni");
WebElement btnLogin = driver.findElement(By.id("ic_C_C8"));
btnLogin.click();
Thread.sleep(10000);
String winTitle = "Role profile selection";
boolean bool = switchWindow(winTitle);
if (bool){
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
else {
System.out.println("Switch to window '" + winTitle + "' failed!");
driver.quit();
}
public static boolean switchWindow(String windowtitle){
String mainWindowsHandle = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
System.out.println(handles.size());
for(String winHandle : handles){
driver.switchTo().window(winHandle);
System.out.println(driver.getTitle());
if(driver.getTitle().toLowerCase().equals(windowtitle)){
return true;
}
}
driver.switchTo().window(mainWindowsHandle);
return false;
}
When I tried to print the window titles in collection, it is only printing the parent window and not the other windows. I am not able to guess what is happening since nothing can be seen and it is headless testing. Please suggest me is there any other way so that I can test the app with many browser windows.

Actions act = new Actions(d);
act.contextClick(elements).sendKeys("W").perform();
Set<String> win = d.getWindowHandles();
Iterator <String> itrwin = win.iterator();
String parent = itrwin.next();
String child = itrwin.next();
d.switchTo().window(child);
identify an web element first using findElement() and store it in element.

Related

Selenium Chrome Driver Trouble Selecting or Inputting for Login

I am trying to setup a tool to monitor my Plex account. I am using Chrome Driver to try and login to my Plex account with an email and password. I cannot manage to locate the input fields no matter what I try, whether by ID, XPath etc. I have run a test with the Selenium Chrome Plugin and it manages to to find the element by ID but when running the following Java code I cannot get the driver to find the email and password fields. The extra code is to deal with the Cookies pop up and seems to work, at least it dismisses the pop up.
...
File file = new File("src/chromedriver88.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
LOGGER.info("Got Chrome driver - " + file.exists());
ChromeOptions options = new ChromeOptions();
options.addArguments("no-sandbox");
driver.get("https://www.plex.tv/en-gb/sign-in/");
// Sort out the cookies pop up if it's there
boolean present;
try {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/a[2]"));
present = true;
} catch (NoSuchElementException e) {
present = false;
}
if (present) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/a[2]")).click();
}
// Wait for log in button to exist
WebDriverWait wait = new WebDriverWait(driver, 30);
#SuppressWarnings("unused")
WebElement elementLogin = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("email")));
// Send log in details
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("...");
WebElement pwd = driver.findElement(By.id("password"));
pwd.sendKeys("...");
// Click log in
driver.findElement(By.xpath("//html/body/div[1]/div/div/div/div[1]/form/button")).click();
Your email and password input inside a frame:
<iframe src="..." id="fedauth-iFrame"
#document
You need switch it first, use .frameToBeAvailableAndSwitchToIt:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("fedauth-iFrame")));
WebElement username = wait.until(ExpectedConditions.elementToBeClickable(By.id("email")));
username.sendKeys("email");
WebElement pwd = wait.until(ExpectedConditions.elementToBeClickable(By.id("password")));
pwd.sendKeys("password");

how to select the auto popup hotel names in a hotel booking site in Selenium

I am working on automating the following hotel booking site. I need to select the auto popup hotel name once I type the hotel in the first search box...I don't know how to do this.
I have navigated through the link and clicked Demo, then clicked the first link that appeared on the page.
I tried to click on the first search box and I need to enter a hotel from the auto popup list...I don't know how to do this because this has no PAC-item...
https://www.phptravels.net/home
public class Question1 {
WebDriver Driver = null;
WebDriverWait wait = null;
String url = "https://phptravels.com/demo/";
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
options.addArguments("--disable-popup-blocking");
Driver = new ChromeDriver(options);
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
wait = new WebDriverWait(Driver, 25);
String winHandle = Driver.getWindowHandle();
//Driver.switchTo().window(winHandle);
//new WebDriverWait(Driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='webpush-onsite']")));
//new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#deny.button.close"))).click();
}
#Test
public void f() {
Driver.get(url);
System.out.println("*****In the main page*****");
String xpathDemo = "//*[#id=\"mega-nav-navigation\"]/div/ul[1]/li[2]/a";
Driver.findElement(By.xpath(xpathDemo)).click();
String Title = "PHPTRAVELS | Travel Technology Partner";
/*try {
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")));
Driver.findElement(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")).click();
} catch(Exception e) {
System.out.println("No popup..."+ e.getMessage());
}
*/
String username = Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[3]/div[2]/div")).getAttribute("innerText");
username = username.substring(6) ;
String password = username.substring(30);
System.out.println("Username text :"+username + "\npassword is:"+password);
Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/a")).click();
utils.HelperFunctions2.switchToWindow(Driver, Title);
Driver.findElement(By.xpath("//*[#id=\"s2id_autogen16\"]")).click();
Driver.findElement(By.xpath("/html/body/div[7]/ul")).click();
}
#AfterTest
public void afterTest() {
Driver.quit();
}
}
Below xpath is result of 1st hotel, changing the index it will intreact with rest of the elements.
After filing text to the hotel text box.
give Thread.sleep(2000);
use below xpath. I hope it will work
(.//ul[#class='select2-results']/following::div[#class='select2-result-label'])[2]
I have already built bots, auto image pickers and more and I have never used the By.xpath method. Classname is much easier to use!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
Driver.findElement(By.className(getInputFocusId).click();
//now focused!
String text = Driver.findElement(By.className("select2-match").getText();
//text is the first default search match of the list.
}
There is also a more complicated way.
In Selenium you can sendKeys to an Element.
If the input element is focused the first match is also focused.
By clicking on Enter the focused match will be searched and displayed in the input element.
Finally you have to read the data from the input Element!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
WebElement element = Driver.findElement(By.className(getInputFocusId);
element.click();
//element.sendKeys(Key.DOWN);
element.sendKeys(Key.ENTER);
String text = element.getText();
//this is the text of the first search match
//if you want to get the second or third just repeat sending the DOWN key.
}
IMPORTANT: Make sure to run each line delayed (200ms is a good time). This helps you finding errors... For example in the Instagram Auth Process I delayed a lot of lines, and it finally worked!
I hope my answer helps you!!!

Selenium webdriver not logging into live.com

I've been attempting to login to live.com with the Selenium Webdriver however every attempt results in an invalid email or password. A correct login is used. I tested it in a physical browser. I'm uncertain if this is the case but I believe sendkeys is not working. Code below.
protected static Map<String,String> settings = new HashMap<String,String>();
public static WebDriver pwb;
In Main:
// Default settings
settings.put("browser","chrome");
settings.put("os","WINDOWS8");
// Sort arguments and put into HashMap
grab(args);
// Set browser settings
DesiredCapabilities cap = DesiredCapabilities.htmlUnitWithJs();
cap.setBrowserName(settings.get("browser"));
cap.setPlatform(Platform.extractFromSysProperty(settings.get("os")));
d.log(cap.asMap().toString());
// Create web browser object
pwb = new HtmlUnitDriver(cap);
login();
In login():
Load("http://login.live.com",0); // custom load function
d.log(pwb.getTitle());
if(pwb.getTitle().contains("Sign in to your")){ // Full login
d.log("Executing full login.\nEmail:" + settings.get("email") + "\nPassword:"+settings.get("password"));
// if (pwb instanceof JavascriptExecutor) {
// ((JavascriptExecutor) pwb).executeScript("document.getElementsByName('login')[0].click();"); //value = " + settings.get("email") + "");
// ((JavascriptExecutor) pwb).executeScript("document.getElementsByName('passwd')[0].click();"); //.value = " + settings.get("password") + "");
// }
// TODO get login working
pwb.findElement(By.id("i0116")).clear();
pwb.findElement(By.id("i0116")).sendKeys(settings.get("email"));
pwb.findElement(By.id("i0118")).clear();
pwb.findElement(By.id("i0118")).sendKeys(settings.get("password"));
pwb.findElement(By.name("SI")).click();
// Attempted = true;
}
If anymore information is needed please let me know.

Selenium Webdriver to handle java script text box

I am trying to specify zip code to a input field to fetch the restaurant locations. I am able to specify the zip code and unable to hit the enter key. As its doesn't has enter button it needs to be handled via javascript. Need help in resolving issue:
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
String baseURL = "http://www.thecheesecakefactory.com/";
driver.get(baseURL);
// Go to Menu
driver.findElement(By.xpath("//*[#id='topNav']/li[1]/a")).click();
// Click on Pizza
driver.findElement(By.xpath("//*[#id='firstScroller']/li[7]/a")).click();
// Select Hawallian Pizza
driver.findElement(By.xpath("//*[#id='secondScroller']/li[6]/a")).click();
//String pageTitle = "Hawaiian Pizza";
String aTitle = driver.getTitle();
if (aTitle.equalsIgnoreCase("Hawaiian Pizza")){
System.out.println("Yes its Hawaiian Pizza");
System.out.println(driver.getTitle());
}
//Click to order and get locations
driver.findElement(By.xpath("//*[#id='receiptMenu']/div[1]/div[3]/div/a/b")).click();
WebElement element;
element = driver.findElement(By.xpath("//*[#id='location_box']/div[2]/input"));
element.sendKeys("84604", Keys.ENTER);
}
WebElement element;
element = driver.findElement("//*[#id='location_box']/div[2]/input");
element.sendKeys("84604", Keys.ENTER);
There is an typo error in the above code.
WebElement element;
element = driver.findElement(By.xpath("//*[#id='location_box']/div[2]/input"));
element.sendKeys("84604", Keys.ENTER);
I checked the code it is working fine.

How to use JavaScript with Selenium WebDriver Java

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.

Categories

Resources