Handling right click menu items in selenium java - java

I want to right click and go the 5th option that is "copy link address".
I have tried the following code and this is the only thing i could i could find on then internet
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.xpath("//*[(#id = \"u_0_1n\")]"));
TimeUnit.SECONDS.sleep(2);
actions.contextClick(elementLocator).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
This code actually scrolls the page downward instead of moving down the right click menu as if the right click menu was never there.

Using context clicks is not something I would recommend as it violates Parallel Testing Best Practices
The tests need to be small, atomic, and autonomous and your current approach assumes that the browser has to be in focus. It means that you will neither be able to do anything while the test is running nor run the tests in parallel.
So instead I would suggest:
Extract href attribute from the link you want to click
Use JavascriptExecutor and Window.open() function in order to open the link in the new tab
Switch to the new tab
Example code:
WebElement link = driver.findElement(By.xpath("//*[(#id = \"u_0_1n\")]"));
String url = link.getAttribute("href");
driver.executeScript("window.open('" + url + "');");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));

Related

How can I scroll mouse in specific menu in main window in Java Selenium WebDriver

I am trying to find a web element in Chrome with help of Selenium WebDriver.
When the driver launches the URL, a list of projects is being displayed and the driver has to select a specific project from that list.
As long as that project is on top of the list, it's ok and can find the project, however if project is at the very bottom of the list (as per list has been ordered alphabetically and say record 57 from list is tried to be selected), test keeps failing and driver can't find the web element!!!
I finally got to this point that I need to scroll my list till that item shows up, but as per this scroll bar is in that menu not in the main window this command is not even executed!
Do I need to identify the project menu to driver at all? how can I scroll down that project menu in the window? I don't want to scroll the main Web window, I need to scroll in the project list only.
I tried all the possible solutions and was surfing all over the Stack Overflow forum as well as internet but couldn't fix this error.
It would be great if you guys have a look at this code bellow and give me some advice. Please let me know if I have to provide more information. Good to mention here that I am reading the "projectName" from spreadsheet.
// Initially I need to hover the mouse on Select Project menu.
Actions action = new Actions(driver);
WebElement list = driver.findElement(By.xpath("//*[#id=\"gridview-1032\"]"));
action.moveToElement(list);
JavascriptExecutor js = (JavascriptExecutor) driver;
// Now I need to scroll down till find my desire project in the list.
WebElement Project = driver.findElement(By.xpath("//*[text()= '"+ projectName +"']"));
js.executeScript("arguments[0].scrollIntoView(true);",Project);
Project.click();
Actual result:
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
no such element: Unable to locate element:
{"method":"xpath","selector":"//*[text()= 'projectName']"}
Expected result:
Find the element in the list and click on that item to launch the project!
Here below is the code that worked for me.This code works fine in your case
Actions action = new Actions(driver);
WebElement list = driver.findElement(By.xpath("//*[#id=\"gridview-1032\"]"));
action.moveToElement(list);
JavascriptExecutor js = (JavascriptExecutor) driver;
// Now I need to scroll down till find my desire project in the list.
WebElement Project = driver.findElement(By.xpath("//*[text()= '"+ projectName +"']"));
js.executeScript("arguments[0].click();",Project);
I found an alternative solution for this question which is simpler:
// Create instance of Javascript executor
JavascriptExecutor je = (JavascriptExecutor) driver;
//Identify the WebElement which will appear after scrolling down
WebElement Project = driver.findElement(By.className("x-grid-item-container"));
// now execute query which actually will scroll until that element is not appeared on page.
je.executeScript("arguments[0].scrollIntoView(true);",Project);
//Login to desired project
Project.click();
I thought this might be an issue for someone else, I am adding my solution as well, it might be helpful:
//it find the list and scroll 3000 pixel
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver6);
eventFiringWebDriver.executeScript("document.querySelector('#gridview-1032').scrollTop=3000");
//find the project and login
WebElement Project = driver6.findElement(By.xpath("//*[text()= '"+ projectName +"']"));
Project.click();

Selenium Webdriver ElementNotVisibleException using Java

Having reviewed posts on this issue before, but problem persists.
http://preview.harriscountyfws.org/ is a public site, pertaining to this question.
I'm trying to click on a dropdown and select "Channel Status" from the Rainfall dropdown.
I get the following error:
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible: Element is not currently visible and may not be manipulated
I am attaching screenshot with code, but you may also visit the site and press F12 to look at the code.
Here is my current code based on research I have done so far:
Select dropdown = new Select(driver.findElement(By.id("siteType")));
WebElement triggerDropDown = driver.findElement(By.className("k-i-arrow-s"));
triggerDropDown.click();
dropdown.selectByVisibleText("Channel Status");
dropdown.selectByIndex(1);
Neither of the last two code statements shown work (dropdown.select...)
Both result in ElementNotVisibleException.
Well that's not true, because by pressing the triggerDropDown.Click(), the choices are visible!
Click Here For Screenshot
use the below code:
driver.get("http://preview.harriscountyfws.org/");
driver.manage().window().maximize();
Thread.sleep(2000);//use wait using until instead of this wait
WebElement elem = driver.findElement(By.xpath("//span[text() = 'Rainfall']"));
elem.click();
Thread.sleep(2000);
for(int i = 0; i <= 2; i++){//2 is used bacause u have 2 options
Actions actions = new Actions(driver);
actions.sendKeys(Keys.DOWN).build().perform();//press down arrow key
Actions actions2 = new Actions(driver);
actions2.sendKeys(Keys.ENTER).build().perform();//press enter
}
this will click on channel status button.
This is a strange one. I could click on the dropdown easily but clicking on "Channel Status" was not working. There's something about that dropdown that is not acting "normal". I tried the typical WebDriverWait but it doesn't work. Selenium is not waiting for it properly or something else is going on. I rarely recommend Thread.sleep() but in this case I can't figure out a way around it.
The code below works.
String searchText = "Channel Status";
driver.findElement(By.cssSelector("span.k-widget.k-dropdown.k-header")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//li[text()='" + searchText + "']")).click();

Opening a link in new window

I need to open a link in a new window with Selenium. I found the following 2 (assume we is the WebElement and I have already found it and myWait just performs a wait for x milliseconds):
1)
Actions act = new Actions(driver);
act.contextClick(we).perform();
myWait(1000); // allow the menu to come up
act.sendKeys(which).perform();
2)
we.sendKeys(Keys.CONTROL + "t");
In #1 I see the menu come up, but the sendKeys does not work (oh, by the way the "which" in sendKeys is a "t"). In #2 it simply ignores it.
In #1 is the menu that comes up in a new window already? Do I have to driver.switchTo()? or if not, what am I doing wrong?
Also, is there another way to do this? we is an element of form <a href=blah> and a regular click opens fine.
You can try the below code to open a link in a new window:
Actions newTab= new Actions(driver);
WebElement link = driver.findElement(By.xpath("//xpath of the element"));
//Opening the link in new window
newTab.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
Note: After you've opened the link a new window, to get control of it, you need to get the handle of this child window, switch to it using driver.switchTo.window("childwindowhandle") and take further actions. And, after that you can close it and switch back to the Parent window(original one) and take actions here (Make sure to get the parent window handle before you open the link in a new window, so that switching back to it is easier).

How can i select text from browser screen with help of mouse events in selenium?

I am trying to select text which is already present on the browser.
I want to select that particular text and perform right click operation on it.
However, the page on the browser has disabled right click.
How can I select text in such situation?
Using a normal web browser without Selenium the only workaround that I can think about is to disable javascript to stop the script that prevents you from right clicking. So it should also work with a browser controlled by Selenium Webdriver.
I don't know if it will be OK for you because your website may be relying on javascript for essential features.
However if you don't need Javascript for your Selenium test you can try the following when you launch your driver :
FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);
I assume that you already know how to perform a right click because your question was only about dealing with the problem preventing you from doing this right click. But if not, you can also refer to this answer :
Select an Option from the Right-Click Menu in Selenium Webdriver - Java
Edit:
I'm sorry I really thought you could use Selenium actions to select the text you want but after some tests I didn't manage to perform a click and drag to select a text. The only thing that works for me in Chrome or Firefox is the following. It looks for a <p>which contains some text and then perform a double click to select a word.
driver.get("http://en.wikipedia.org/wiki/Java_(programming_language)");
WebElement text = driver.findElement(By.xpath("//p[contains(text(),'Java is')]"));
Actions select = new Actions(driver);
select.doubleClick(text).build().perform();
However it only highlighs one word in the html element that contains your text, so it's not really convenient.
I've also tried to do Ctrl+F and type the text so that the web browser automatically select it but the browser doesn't do anything when executing :
Actions search = new Actions(driver);
search .sendKeys(Keys.chord(Keys.CONTROL,"+f")).sendKeys("Java is").build().perform();
It seems that Selenium can only send keys events to the html elements and not to the browser (in the case of ctrl+F).
I don't really see a solution for now, let's see if someone else can find a workaround. It's an interesting issue, it would also be useful for me to select a text the way you described
Move to middle of the element
Actions builder = new Actions(webDriverObject);
builder.moveToElement(element).build().perform();
Move to starting of element, click and hold, move to end
Integer width = element.getSize().getWidth();
Actions newBuilder = new Actions(webDriverObject);
newBuilder.moveByOffset(width/2,0).clickAndHold.moveByOffset(width,0).release().build().perform();

Not able to switch to pop-up window and find any elements in pop-up in Webdriver using Java

I have an application in which i tried clicking on a button and in return it will pop-up a window for filling a new user form. This is not really like a pop-up window, because it has some input fields as well as "save " and "cancel" button. It looks similar to pop-up window in facebook.
Here the code i tried with
Set beforePopup = driver.getWindowHandles();
driver.findElement(By.xpath("/html/body/div/div/div/div[3]/div/div[2]/div[2]/table/tbody/tr/td[3]/table/tbody/tr/td[2]/em/button")).click();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
Set afterPopup = driver.getWindowHandles();
afterPopup.removeAll(beforePopup);
if(afterPopup.size() == 1) {
driver.switchTo().window((String)afterPopup.toArray()[0]);
}
//driver.switchTo().window("Add New User");
//selenium.type("userDetailsBean.firstName","alan1");
//WebElement btnStartQueryInside = driver.findElement(By.xpath("//html/body/div[14]/div/div/div/div/span"));
//btnStartQueryInside.getText();
System.out.println(driver.getTitle());
WebElement firstName = driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/form/div/div/input"));
firstName.sendKeys("alan1");
//driver.switchTo().alert();
//driver.findElement(By.xpath("//html/body/div[14]/div/div/div/div")).getText();
//WebElement firstName=driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/form/div/div/input"));
//firstName.sendKeys("alan1");
/*WebElement lastName=driver.findElement(By.id("userDetailsBean.lastName"));
lastName.sendKeys("harper");
WebElement emailadd=driver.findElement(By.id("userDetailsBean.userEmail"));
emailadd.sendKeys("alan1#derik.com");
WebElement username=driver.findElement(By.id("userDetailsBean.userName"));
username.sendKeys("xalan1");
WebElement password=driver.findElement(By.id("adminPassword"));
password.sendKeys("Derik123");
WebElement repassword=driver.findElement(By.id("adminPassword2"));
repassword.sendKeys("Derik123");
driver.findElement(By.xpath("//html/body/div[2]/div/div/div/div/div[2]/div/div/table/tbody/tr/td/table/tbody/tr/td[2]/em/button")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);*/
Please note that in code I commented some input field filling, because I thought first I will make it working just for 1st field. Please help me how to proceed.
the problem is after clicking the pop-up button, I'm not sure if the control switches to pop-up window or not. the gettitle after pop-up gives the main window title. and it is not able to find the first input field using the xpath or id.
The term window in Selenium means the actual browser window, not frames or just divs. Therefore, your logic is wrong, getWindowHandles() and driver.switchTo().window("Add New User") are not what you are after.
What you need is driver.switchTo().frame().
driver.switchTo().defaultContent(); // optional, use only if driver is already in an iframe
WebElement editUserForm = driver.findElement(By.cssSelector("iframe[src*='editUserForm']"));
// there are other overloads (by frame name, index, id) and locators can be used here.
driver.switchTo().frame(editUserForm);
// make sure your locator here is correct
WebElement lastName = driver.findElement(By.id("userDetailsBean.lastName")); // I doubt this is correct
// from your screenshot, I'd suggest By.cssSelector("[id*='userDetailsBean.lastName'] input")
lastName.sendKeys("harper");
Also just a kindly heads up, your code smells.
Your implicitlyWait wait usage seems wrong, please read the
documentation and the post.
Where did you get selenium.type("userDetailsBean.firstName","alan1");? Did you just copy the line from somewhere else? This looks like Selenium RC to me.
Why driver.switchTo().alert()? Have you read the documentation on what's this for?
Please don't use absolute xpath.
Try use page object if you haven't done that in your real project. (It's fine if you just want to illustrate the problem here)

Categories

Resources