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");
}
}
Related
I am starting to learn how to handle multiple tabs in a browser using Selenium with Java. looks like my code below is not working.
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static void main(String[] args) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
//Get Data Policy
WebElement we= driver.findElement(By.linkText("Data Policy"));
//Click Data Policy link
we.click();
//Create an arrayList
ArrayList<String> s1= new ArrayList<String>(driver.getWindowHandles());
for(String s2:s1)
{
if(!(s2.equalsIgnoreCase(parent)))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
}
}
Please let me know how can I display the title 'Data Policy' without using
getWindowHandles().
getWindowHandles() works pretty fine but before invoking getWindowHandles() you have to induce WebDriverwait as follows :
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
driver.findElement(By.linkText("Data Policy")).click();
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> s1= driver.getWindowHandles();
for(String s2:s1)
{
if(!parent.equalsIgnoreCase(s2))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
Console Output :
Parent Window is4294967297
4294967303
get title of windowData Policy
Just put Thread.sleep(3000); after clicking on Data Policy link.
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
//D:\new folde backup\Selenium_project\seleniumproject\testNG_practice\driver
System.setProperty("webdriver.gecko.driver", "./driver/geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent = driver.getWindowHandle();
System.out.println("Parent Window is" + parent);
// Get Data Policy
WebElement we = driver.findElement(By.linkText("Data Policy"));
// Click Data Policy link
we.click();
// Create an arrayList
Thread.sleep(3000);
ArrayList<String> s1 = new ArrayList<String>(driver.getWindowHandles());
System.out.println(s1);
for (String s2 : s1) {
if (!(s2.equalsIgnoreCase(parent))) {
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window" + driver.getTitle());
}
}
}
}
Output:-
Parent Window is4294967297
[4294967297, 4294967301]
4294967301
get title of windowData Policy
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);
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);
}