I have gecko driver installed already.
I am little bit confused in page scroll down.Console is not showing me any error as I have written Test Case failed if (if condition fails):
package PackageQandle;
//import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
//import junit.framework.Assert;
public class Adduser {
public static void main(String[] args) throws Throwable {
System.setProperty("webdriver.gecko.driver","C:/Users/sudhir/geckodriver-v0.18.0-win32/geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://prod4.qandle.com");
WebDriverWait webwait = new WebDriverWait(driver,120);
webwait.until(ExpectedConditions.elementToBeClickable(driver.findElementByXPath(".//*[#id='login-email']")));
WebElement web = driver.findElementByXPath(".//*[#id='login-email']");
web.sendKeys("Anil#gmail.com");
WebDriverWait webwait1 = new WebDriverWait(driver,20);
webwait1.until(ExpectedConditions.elementToBeClickable(driver.findElementByXPath(".//*[#id='login-password']")));
WebElement web1 = driver.findElementByXPath(".//*[#id='login-password']");
web1.sendKeys("Abc12345");
WebElement web2 = driver.findElementByXPath(".//*[#id='signInSubmit']");
web2.submit();
//Assert.assertEquals(my_Title, my_ExpectedTitle);
Thread.sleep(5000);
//JavascriptExecutor j = new JavascriptExecutor();
String my_Title = driver.getCurrentUrl();
//System.out.println(my_Title);
String my_ExpectedTitle = "https://prod4.qandle.com/#/";
if(my_Title.equals(my_ExpectedTitle)){
driver.executeScript("Scroll(0,600);");
}else{
System.out.println("Test Case Failed");
}
}
}
I am using this code to inspect element which appears when I scroll down the page.
The Syntax of findElementByXpath must be
driver.findElement(By.xpath(".//*[#id='login-password']"));
Try the below mentioned code for scrolling to element, it worked for me
driver.get("https://prod4.qandle.com");
WebDriverWait webwait = new WebDriverWait(driver,120);
webwait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath(".//*[#id='login-email']"))));
WebElement web = driver.findElement(By.xpath(".//*[#id='login-email']"));
web.sendKeys("Anil#gmail.com");
WebDriverWait webwait1 = new WebDriverWait(driver,20);
webwait1.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath(".//*[#id='login-password']"))));
WebElement web1 = driver.findElement(By.xpath(".//*[#id='login-password']"));
web1.sendKeys("Abc12345");
WebElement web2 = driver.findElement(By.xpath(".//*[#id='signInSubmit']"));
web2.submit();
//Assert.assertEquals(my_Title, my_ExpectedTitle);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String my_Title = driver.getCurrentUrl();
String my_ExpectedTitle = "https://prod4.qandle.com/#/";
if(my_Title.equals(my_ExpectedTitle)){
JavascriptExecutor js = (JavascriptExecutor) driver;
// Mention the xpath of the element to be scrolled for
WebElement tempElement=driver.findElement(By.xpath("//*[contains(text(),'Reports')]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);
}else{
System.out.println("Test Case Failed");
}
If you are using "Chrome" use:
js.ExecuteScript("arguments[0].scrollIntoViewIfNeeded(true);", e)
For "Firefox" and "IE" use:
js.ExecuteScript("arguments[0].scrollIntoView(true);" +
"window.scrollBy(0,-100);", e);
You need to cast driver to JavascriptExecutor type
JavascriptExecutor jse = (JavascriptExecutor) deiver;
WebElement scrollElement = driver.findElement();
jse.executeScript("return arguments[0].scrollIntoView();", scrollElement);
Related
I need to click and highlight the text either by mouse(click, hold and move) or keyboard (LeftShift Right Arrow) action using Selenium. In the below example I need to highlight the number "1643". In real time we use either mouse or Keyboard to highlight or select the text in similar way we want to select/highlight the text. Please help me on this.
<span>
#1643 Welcome <span> User!. Please wait... </span>
</span>
private void SelectByMouseAndClickByCharacterPosition(WebDriver driver, String xPathSelector, int startPosition, int endPosition) {
try {
Actions actions = new Actions(driver);
Thread.sleep(1000);
WebElement element = driver.findElement(By.xpath(xPathSelector));
actions.moveToElement(element);
String selectedElementText = element.getText();
String textToSelect = selectedElementText.substring(startPosition, endPosition);
String highLightSelector = xPathSelector+"[contains(.,'" + textToSelect + "')]";
WebElement highlightElement = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(highLightSelector)));
String selec = highlightElement.getText();
highlightElement.sendKeys(textToSelect);
highlightElement.click();
Thread.sleep(2000);
actions.keyDown(Keys.LEFT_SHIFT);
for(int i=0;i<textToSelect.length(); i++) {
actions.keyDown(Keys.ARROW_DOWN);
}
actions.keyUp(Keys.LEFT_SHIFT);
actions.build().perform();
//actions.clickAndHold().moveByOffset(xcord, ycord);
//actions.pause(3000);
Thread.sleep(2000);
actions.release().perform();
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
As i understand your question that you want to highlight one text from the page.
As the easiest way to do it using javascript executor.
public static void spotlight(WebDriver driver,WebElement element) {
JavascriptExecutor jsexecute = (JavascriptExecutor) driver;
jsexecute.executeScript("arguments[0].setAttribute('style', 'background: red; border: 2px solid green;');", element);
}
Now simply highlighted
public static void main(String[] args) {
driver=new ChromeDriver();
driver.get("https://www.google.com");
WebElement searchbar=driver.findElement(By.xpath("//input[#name=\"q\"]"));
spotlight(driver,searchbar);
searchbar.sendKeys("Hello World");
}
Result
Complete program is
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class test {
WebDriver driver;
public static void spotlight(WebDriver driver, WebElement element) {
JavascriptExecutor jsexecute = (JavascriptExecutor) driver;
jsexecute.executeScript("arguments[0].setAttribute('style', 'background: red; border: 2px solid green;');", element);
}
#Test
public void test(){
driver=new ChromeDriver();
driver.get("https://www.google.com");
WebElement searchbar=driver.findElement(By.xpath("//input[#name=\"q\"]"));
spotlight(driver,searchbar);
searchbar.sendKeys("Hello World");
}
}
I have the following problem: When I run my code I want to open new tab(not link in new tab) but after I open it I can't focus on it. The focus is still on the old one.
Here is my code:
WebDriver driver = new ChromeDriver();
driver.get("url for the initial tab");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 15);
// Open tab for email generation
String url = "url for tab 2";
((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String site = driver.getCurrentUrl();
if(driver.findElements(By.xpath("xpath here")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
System.out.println("Current URL:" + site); //I get the initial url.
Also after I focus on the new tab how to switch to the old one?
Thanks
Here is the Answer to your Question:
I have used your own code and rewritten it with a few tweaks to work with the WindowHandles using Set from java.util. Now your code opens https://google.com first, prints the Page Title, then opens the URL https://www.facebook.com/ in a new tab shifts its focus to the new tab with the URL https://www.facebook.com/, prints the Page Title and the current URL:
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Q44970997_newTabURL
{
public static void main(String[] args)
{
String site = null;
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
driver.manage().window().maximize();
System.out.println(driver.getTitle());
String first_tab = driver.getWindowHandle();
String url = "https://www.facebook.com/";
((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
site = driver.getCurrentUrl();
Set<String> tab_handles = driver.getWindowHandles();
Iterator<String> itr = tab_handles.iterator();
while(itr.hasNext())
{
String next_tab = itr.next();
if(!first_tab.equalsIgnoreCase(next_tab))
{
driver.switchTo().window(next_tab);
System.out.println(driver.getTitle());
site = driver.getCurrentUrl();
System.out.println("Current URL:" + site); //You get the new url.
}
}
}
}
Let me know if this Answers your Question.
package Chrome_Packg;
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.interactions.Actions;
public class testFirefox_DragDrop {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();
driver.get("http://jqueryui.com/droppable/");
WebElement drag=driver.findElement(By.xpath("/html/body/div[1]"));//drag element
WebElement drop=driver.findElement(By.xpath("/html/body/div[2]"));//drop element
Actions action=new Actions(driver);
Thread.sleep(3000);
action.dragAndDrop(drag, drop).perform();
}
}
After executing the code, using Run as java application, in output I am getting nothing.
Here is the code snippet for the same website that you are trying on and you can also find the example here selenium Drag and Drop example
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://jqueryui.com/droppable/");
//Wait for the frame to be available and switch to it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector(".demo-frame")));
WebElement Sourcelocator = driver.findElement(By.cssSelector(".ui-draggable"));
WebElement Destinationlocator = driver.findElement(By.cssSelector(".ui-droppable"));
dragAndDrop(Sourcelocator,Destinationlocator);
String actualText=driver.findElement(By.cssSelector("#droppable>p")).getText();
Assert.assertEquals(actualText, "Dropped!");
I want to be able to scroll the subscriptions list of my personal YouTube page, how do I do this? I have written code that allows me to scroll the main page, any ideas as to how the code could be tweaked to scroll the "My subscriptions" section of the YouTube page that appears when signed into YouTube?
package Check;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class java {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.youtube.com");
Thread.sleep(2500);
driver.findElement(By.xpath("//button[contains(.,'Sign in')]")).click();
Thread.sleep(1500);
driver.findElementById("Email").sendKeys("<My username>");
driver.findElementById("Passwd").sendKeys("<My password>");
driver.findElementById("signIn").click();
//driver.findElement(By.xpath("//button[contains(.,'Sign in')]")).click();
Thread.sleep(3500);
driver.findElementByCssSelector("div[id='identity-prompt-account-list'] > ul > label + label").click();
driver.findElementById("identity-prompt-confirm-button").click();
Thread.sleep(2500);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +
"document.body.scrollHeight,document.documentElement.clientHeight));");
Thread.sleep(5000);
driver.quit();
}
}
I have found by a method of trial and error a method that works, by the CSS selector appears to be limited to finding up to the 35th sibling so in the light of this limitation here is the code that I came up with this works very well for what I want to accomplish. Here is my script below:
package Check;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;
public class java2 {
public static void main(String[] args) throws InterruptedException {
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.youtube.com");
Thread.sleep(2500);
driver.findElement(By.xpath("//button[contains(.,'Sign in')]")).click();
Thread.sleep(1500);
driver.findElementById("Email").sendKeys("<User name>");
driver.findElementById("Passwd").sendKeys("<Password>");
driver.findElementById("signIn").click();
Thread.sleep(4000);
driver.findElementByCssSelector("div[id='identity-prompt-account-list'] > ul > label + label").click();
driver.findElementById("identity-prompt-confirm-button").click();
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor)driver;
int i =0;
String CSSText = "ul[id='guide-channels'] > li";
do {
if (driver.findElementByCssSelector(CSSText).getText().equals("Josie Outlaw")){
break;
}
CSSText = CSSText + " + li";
i++;
} while (i<35);
js.executeScript("document.getElementsByClassName(\"vve-check overflowable-list-item guide-channel\")["+i+"].scrollIntoView(false);");
Thread.sleep(1500);
js.executeScript("document.getElementsByClassName(\"vve-check overflowable-list-item guide-channel\")["+i+"].scrollIntoView(true);");
Thread.sleep(10000);
driver.quit();
}
}
I have used the code below trying to open same multiple window "Google". Kindly help me in editing this and explaining how to handle this .
driver.switchTo().window("gbar");//not sure how to use this
and below code tried in Selenium:
package Testing;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.*;
public class Float {
public static void setUp() {
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
}
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.name("q"));
element.click();
WebDriverWait wait = new WebDriverWait(driver, 80);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("q")));
element.sendKeys("hi");
element.clear();
Thread.sleep(2000);
element.sendKeys("hey");
element.submit();
setUp();
driver.switchTo().window("gbar");// //* not sure how to use this *///
WebElement element1 = driver.findElement(By.name("q"));
element1.click();
element1.sendKeys("hi");
element1.clear();
element1.sendKeys("hey");
element1.submit();
driver.quit();
}
}
You can get a handle to your window via driver.getWindowHandle()and you can switch to a window with driver.switchTo().window("handle");.
If you want to open a new window you can click on a link with target="_blank" on the website or execute JavaScript to open a new window. Then you'll find another handle in driver.getWindowHandles(). A possible way could be:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
List<String> knownHandles = new ArrayList<String>();
knownHandles.add(driver.getWindowHandle());
((JavascriptExecutor)driver).executeScript("window.open();");
// find the new handle. we are getting a set
for (String handle : driver.getWindowHandles()) {
if (!knownHandles.contains(handle)) {
knownHandles.add(handle);
break;
}
}
String newHandle = knownHandles.get(knownHandles.size() -1 );
driver.switchTo().window(newHandle);
driver.get("https://www.google.com");
Another way is to inject the anchor and click it via JavaScript.
//Store the current window handle
String winHandleBefore = driver.getWindowHandle();
//Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
driver.manage().window().maximize();
//Close the new window, if that window no more required
driver.close();
//Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
Here is a sample example handling multiple windows:
public class Mytesting {
WebDriver driver = new FirefoxDriver();
#Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
#Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
// Get and store both window handles in array
Set<String> AllWindowHandles = driver.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code = "+AllWindowHandles.toArray()[1]);
//Switch to window2(child window) and performing actions on it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[#name='fname']")).sendKeys("My Name");
driver.findElement(By.xpath("//input[#value='Bike']")).click();
driver.findElement(By.xpath("//input[#value='Car']")).click();
driver.findElement(By.xpath("//input[#value='Boat']")).click();
driver.findElement(By.xpath("//input[#value='male']")).click();
Thread.sleep(5000);
//Switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//option[#id='country6']")).click();
driver.findElement(By.xpath("//input[#value='female']")).click();
driver.findElement(By.xpath("//input[#value='Show Me Alert']")).click();
driver.switchTo().alert().accept();
Thread.sleep(5000);
//Once Again switch to window2(child window) and performing actions on it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[#name='fname']")).clear();
driver.findElement(By.xpath("//input[#name='fname']")).sendKeys("Name Changed");
Thread.sleep(5000);
driver.close();
//Once Again switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//input[#value='male']")).click();
Thread.sleep(5000);
}