unable to take screenshot of mouseover in selenium - selenium-webdriver

I am trying to take screenshot of sub menu which happens on hovering in selenium using TakesScreenshot. But this is not working. Screenshot is taken but sub menu is not present in the image.
I have also tried using implicit wait after hover, but nothing worked.
Please suggest a method to capture screenshot of the sub menu.
contactUs.hoverHM();
screenshot = ((TakesScreenshot) PageFactoryBase.getSharedWebDriver()).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");

This did the trick for me. I am pretty sure it will work for you.
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseover_mouseout");
_driver.SwitchTo().Frame(_driver.FindElement(By.Id("iframeResult")));
Actions builder = new Actions(_driver);
builder.MoveToElement(_driver.FindElement(By.TagName("p"))).Build().Perform();
var screenshot = ((ITakesScreenshot)_driver).GetScreenshot();
var filename = new StringBuilder("D:\\");
filename.Append(DateTime.Now.ToString("HH_mm_ss dd-MM-yyyy" + " "));
filename.Append("test");
filename.Append(".png");
screenshot.SaveAsFile(filename.ToString(), System.Drawing.Imaging.ImageFormat.Png);
After hovering mouse on the text, it turns yellow and below is the screen shot that I took.

Below is another approach where you can use 'Print screen' Key in your Test code and get the image from the clipboard in the system.
What is have done is used KeyEvent 'PRTSC' to get the Image into the system clipboard and then get the system clipboard to write it to a file. I hope it will also copy the mouseover.
Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_PRINTSCREEN);
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable content = clip.getContents(null);
BufferedImage img = (BufferedImage)content.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(img, "png", new File("D:\\test.png"));

I have tried the same scenario but for clickAndHold for hover skin. It worked for me with the help of Actions as below:
WebElement elm = driver.findElement(By.id("btn1"));
Actions builder = new Actions(driver);
Action act = builder.clickAndHold(elm).build();
act.perform();
try {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\Img\\screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
act = builder.release(elm).build();
act.perform();
You can instead replace clickAndHold with moveToElement Mouse hover the element. take the screenshot then release the element or move away from it.

Thanks everyone for answering on this thread.
I am able to take screenshot using robot as suggested by Vivek.
builder.moveToElement(getSharedWebDriver().findElement(By.xpath("//div[#class='brand section']/ul/li[#class='active hasflyout']"))).perform();
Robot robot = new Robot();
Point point;
point = getSharedWebDriver().findElement(By.xpath("//div[#class='brand section']/ul/li[#class='active hasflyout']")).getLocation();
int x = point.getX();
int y = point.getY();
robot.mouseMove(x,y);
In ideal case, either perform() or mouseMove() should be used. But somehow in my case, i had to use both the functions.

Related

Element is not clickable at point ... error when using headless browsing

I have this error "org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element is not clickable at point (209, 760)", when I run the piece of code below in headless mode. When it is run with browser displayed I have no error and test passes fine. As you can see below, I trie with waiting, js executor, actions move to element but still no good result. I am using xpath to locate / define the element, and not coordinates. Why is this happening please and how can I solve it? Thanks in advance.
#Test(priority = 1)
public void verifyAddUserWithMarkedMandatoryFields() {
// accessing add user webpage / functionality
userListObject.getAddUserButton().click();
// inserting data to complete form
addOrEditUserPageObject.insertCredentials(userModel.getUsername(), userModel.getEmail(), "", userModel.getPassword());
// clicking Submit when becoming enabled
WebDriverWait myWaitVariable = new WebDriverWait(driver, 5);
myWaitVariable.until(ExpectedConditions.elementToBeClickable(addOrEditUserPageObject.getSubmitButtonAddOrEdit()));
// Actions actions = new Actions(driver);
// actions.moveToElement(addOrEditUserPageObject.getSubmitButtonAddOrEdit()).click().perform();
JavascriptExecutor jse = (JavascriptExecutor)driver;
// jse.executeScript("scroll(209, 760)"); // if the element is on top.
jse.executeScript("scroll(760, 209)"); // if the element is on bottom.
addOrEditUserPageObject.getSubmitButtonAddOrEdit().click();
}
You should add screen size for the headless mode, something like this:
Map<String,String> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadsPath); // Bypass default download directory in Chrome
prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.)
ChromeOptions opts = new ChromeOptions();
opts.setExperimentalOption("prefs", prefs);
opts.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080","--ignore-certificate-errors","--no-sandbox", "--disable-dev-shm-usage");
driver = new ChromeDriver(opts);
I put much more things here, the only relevant point here is "--window-size=1920,1080", this should resolve your problem.
The rest is to show how things are managed, including other relevant settings for headless mode.

Draw on a Canvas Using Selenium

I'm using selenium with java (latest for both). Trying to draw on a small canvas area inside a modal in our webapp. The library we used for our canvas was 'signature pad js'. I have confirmed it is not inside an iframe or anything tricky that could be the problem (it's just a regular div.modal-body with a div.signature-input canvas element).
But it is not doing anything. Have looked at many posts here on stackoverflow and most of them seem pretty identical with few variations to try (I've been trying them all).
Here's the latest code I tried:
// Draw a signature of some sort
WebElement element = driver.findElement(Using.locator(SIGNATURE_AREA)); // canvas element
Actions builder = new Actions(driver);
builder.clickAndHold(element).moveByOffset(10, 50).
moveByOffset(50,10).
moveByOffset(-10,-50).
moveByOffset(-50,-10).release().perform();
I've tried all sorts of offsets, and such to no avail.
If anyone has experience with this, would really love a hand.
I think your issue is in the code , I've done this with ruby and it worked fine.. Code in Ruby below (worked in FireFox)
driver.find_element(:xpath, "html/body/div[1]/div[5]/div[2]/canvas").click
element = driver.find_element(:xpath, "html/body/div[1]/div[5]/div[2]/canvas");
driver.action.move_to(element).perform
driver.action.click_and_hold(element).perform
driver.action.move_by(150, 50).click.perform
driver.action.move_to(element).perform
driver.action.click_and_hold(element).perform
driver.action.move_by(100, 50).click.perform
driver.action.move_to(element).perform
driver.action.click_and_hold(element).perform
driver.action.move_by(300, 10).click.perform
sleep (5)
So I have tried same thing using Java for you , and its working fine , Its drawing two lines as expected. The trick is that moveby should not be followed with a click otherwise it will loose focus. Below code is working fine in java and chrome . I used https://sketchtoy.com/ to draw on canvas
public class BrowserTesting {
WebDriver driver;
#Test
public void test1() throws InterruptedException {
//WebDriverManager.chromedriver().setup();
System.setProperty("webdriver.chrome.driver","C:\\Users\\pathtyourchrome\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
//disable automation info bar
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.get("https://sketchtoy.com/");
WebElement element = driver.findElement(By.xpath("//div[#class='sketch-canvas-container']/canvas"));//canvas element
Actions builder = new Actions(driver);
builder.moveToElement(element).perform();
builder.clickAndHold(element).perform();
builder.moveByOffset(150, 50).perform();
builder.moveToElement(element).perform();
builder.clickAndHold(element).perform();
builder.moveByOffset(100, 50).perform();
builder.moveToElement(element).perform();
Thread.sleep(5000);
//driver.quit();
}
}
See this screen shot for the drawing:
Let me know if this worked!

How to Test Print-preview of Chrome browser using Chrome webdriver?

I have tried using switching between windows using
String winHandleBefore = driver.getWindowHandle();
<code to print>
for (String winHandle : driver.getWindowHandles())
driver.switchTo().window(winHandle);
driver.findElement(By.className("cancel")).click();
driver.switchTo().window(winHandleBefore);
This hangs my test case execution after it opens the print preview page.
Also tried with javascript executor method, but no use.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.close()", "");
Please suggest if it's possible to do so.
I have found the answer to my question. I used below code snippet.
//Create a Region for Desktop Screen
ScreenRegion s = new DesktopScreenRegion();
//Find target with below Image in Desktop Screen
Target target = new ImageTarget(new File("Image.png"));
ScreenRegion r = s.find(target);
// Create a mouse object
Mouse mouse = new DesktopMouse();
// Use the mouse object to click on the center of the target region
mouse.click(r.getCenter());
With the help of this snippet you would able to find the print or cancel and do the mouse click event and proceed with selenium tests. This was possible using sikuli API

Selenium Webdriver drag and drop NOT working in Chrome

I used the below code for drag and drop. It worked in Firefoxdriver but NOT in chromedriver.
WebElement dragElement = driver.findElement(By.id(dragid1));
WebElement dropElement = driver.findElement(By.id(dropid1));
Actions builder = new Actions(driver);
Action drag = builder.clickAndHold(dragElement).build();
drag.perform();
Action move = builder.moveByOffset(355, -20).build();
move.perform();
TimeUnit.SECONDS.sleep(2);
Actions release = builder.clickAndHold(dropElement).release();
release.perform();
Please Help!
If you have both source and target IDs, then why don't you try to use drag and drop?
I'm not very good with Java, but here's how I've done it in Python. I hope it helps you a bit.
from selenium.webdriver.common.action_chains import ActionChains
actionChains = ActionChains(driver)
actionChains.drag_and_drop(dragElement, dropElement).perform()
Tried below sample code with chromedriver:2.15, chrome:v43 and is working fine with Chrome.
Sample Code:
System.setProperty("webdriver.chrome.driver","drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(1,TimeUnit.MINUTES);
driver.get("http://jqueryui.com/droppable");
driver.switchTo().frame(0);
WebElement dragElement = driver.findElement(By.id("draggable"));
WebElement dropElement = driver.findElement(By.id("droppable"));
Actions builder = new Actions(driver);
builder.clickAndHold(dragElement).moveToElement(dropElement).release().build().perform();
Try bundling all those seperate Action objects into a single Actions object
Actions act = new Actions(driver);
act.ClickAndHold(dragElement );
act.MoveToElement(dropElement );
act.Release(dragElement );
act.Build().Perform();
Note: For me, in Chrome & IE, sometimes just dragging to an Element was not enough to make it stick there, and I would have to add in an extra act.MoveByOffset(0, 5); before releasing to move just a few pixels, which seems to work
Is there a reason you have to wait for 2 seconds before releasing, or is that just what worked in FF?
I had the same problem but got to override it like this:
//Setup robot
Robot robot = new Robot();
robot.setAutoDelay(50);
//Maximized browser:
robot.keyPress(KeyEvent.VK_F11);
Thread.sleep(2000);
WebElement dragElement = driver.findElement(drag_element);
Actions builder = new Actions(driver);
builder.dragAndDropBy(dragElement,0, 200).build().perform();

Mono winforms app fullscreen in Ubuntu?

Just wondering if there's a known way of getting a Mono System.Windows.Forms application to go fullscreen on Ubuntu/Gnome.
Mono is 2.4.2.3
Ubuntu is 9.10
Doing it on Windows requires a pinvoke, clearly not going to work here.
This is what I get setting window border to none, window position to centre, and state to maximised:
alt text http://dl.dropbox.com/u/116092/misc/permalink/joggler/screenshot01.png
Update.
Have also tried:
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
CTRL-F11
Text = string.Empty; // No caption
MaximizeBox = false;
MinimizeBox = false;
ControlBox = false;
FormBorderStyle = None;
WindowState = Maximized;
FormBorderStyle = FormBorderStyle.None;
Location = new Point(0, 0);
Size = Screen.PrimaryScreen.Bounds.Size;
All of which I end up with the same result.
I have come across a lead which involves a pinvoke involving _NET_WM_STATE_FULLSCREEN but that's as far as I've got with it. Any pointers on that would be appreciated.
_NET_WM_STATE_FULLSCREEN will just get rid of the borders. The GNOME panel will still appear.
According to the following post, the secret is to get rid of the minimum/maximum sizes so that the window manager does the resizing itself:
http://linux.derkeiler.com/Mailing-Lists/GNOME/2010-01/msg00035.html
Here is some documentation on the native spec:
http://standards.freedesktop.org/wm-spec/wm-spec-latest.html
http://www.x.org/docs/ICCCM/icccm.pdf
To talk directly to the X Window System you have to pinvoke into XLib. In order to send something like _NET_WM_STATE_FULLSCREEN you have to have a pointer to the window and also to the display.
I am not sure how to find the display but I can help with a pointer to the window. When running on X, the property Form.Handle should be a pointer to the X window.
Not sure what you mean by "Full Screen" - but I've written several Windows.Forms applications that take over the screen, and without a single PInvoke.
Here's how I configure my main form ...
Text = string.Empty; // No caption
MaximizeBox = false;
MinimizeBox = false;
ControlBox = false;
FormBorderStyle = None;
WindowState = Maximized;
Optionally,
TopMost = true;
Hope this helps.
You need to disable visual effects in ubuntu.
edit:
And make sure your form size is at least screen resolution without borders. If borders are on design time and you are removing them in code you will need something like 1030x796 for a 1024x768 display.
I have been suffered by this problem 2 days and finally i got the solution:
click the 1st icon on left tool bar and search compizconfig program. Go to preference-> unity and you will see there is a tick for unity plugin on the left side. Remove that tick and you will see the top menu bar disappeared.
Though this thread is very old but I still hope I can help anyone who gets this problem and seek for help.
Have you tried this?
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
Unfortunately I have no Ubuntu available right now, but I can see old patches for this in old mono versions...
It should be possible to display every app running inside gnome in fullscreen mode with the "CTRL+F11" hotkey.
Maybe you could try
System.Windows.Forms.SendKeys.Send();
but that is just a guess, I haven't got a Linux running atm to try this. But maybe this helps.
I can't test it at the moment, but have you tried a simple resize?
form.FormBorderStyle = FormBorderStyle.None
form.Location = Point(0, 0)
form.Size = Screen.PrimaryScreen.Bounds.Size
I have worked around this for now by setting the autohide property of the panel.
Not ideal because it depends on the user changing their environment to use my application, but better than nothing.
YMMV. http://fixunix.com/xwindows/91585-how-make-xlib-based-window-full-screen.html
The following worked:
(Inspiration was taken from here: https://bugzilla.xamarin.com/show_bug.cgi?id=40997)
1) sudo apt-get install wmctrl
2) In your code:
Form form = new MainWindow();
form.FormBorderStyle = FormBorderStyle.None;
form.WindowState = FormWindowState.Maximized;
form.Load += (s, e) => {
Process process = new Process {
StartInfo = new ProcessStartInfo {
FileName = "wmctrl",
Arguments = $"-r :ACTIVE: -b add,fullscreen",
CreateNoWindow = true
}
};
process.Start();
process.WaitForExit();
};
Application.Run(form);

Resources