Allure AShot() screenshots in Selenium - java

Im experimenting with Allure aShot() class to take screenshots of specific WebElements on a website I'm working on, and below is the code I used in selenium to make it happen.
Please visit this link, which shows aShot() project documentation:
https://github.com/yandex-qatools/ashot
So My QUESTION is that, where are these AShot() screenshots of the WebElement actually being saved? I used testNG to execute below method and successfully able to generate allure reports but I can't see these screenshots in those reports or anywhere in my framework. Please check below code, it is very difficult to pinpoint the location of these images.
So again, my basic question is: How do we specify selenium to store these AShot() screenshots of the WebElement into a particular file that we want?
I've tried to cast Screenshot class mentioned below to BufferedImage or TakesScreenshot class and use ImageIO.write or FileUtils.copyFile methods to copy these images into a file and store these images there, but I get an error saying, for example, "java.lang.ClassCastException: ru.yandex.qatools.ashot.Screenshot cannot be cast to org.openqa.selenium.TakesScreenshot" and I've tried other methods as well, unsuccessfully.
Please help me resolve this issue, how do we know/specify where these AShot() screenshots are being saved?
public WebDriver driver;
#Test
public void getAShotImage() {
driver.get("http://....../");
WebElement element = driver.FindElement(By.xpath(".............."));
AShot shot = new AShot();
shot.takeScreenShot(driver, element);
OR
shot.coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver, element);
}

You can attach your screenshots by returning byte array from the method. Look at the following example:-
#Attachment(value="Screenshot", type="image/png")
private static byte[] captureScreenshot(Webdriver driver)
{
byte[] screenshot = null;
screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
return screenshot
}
Above code does not use Ashot but it shows how you need to attach files. Also, if you are still not able to see your screenshots, check if your steps are displayed in your report.If not then probably you are missing javaagent as discussed in FAQ

AShot returns the Screenshot object, that contains the image of your element and information for comparison of screenshots. In this case you can use getImage() method to get the image.
new AShot().takeScreenshot(....).getImage();
The Screenshot will contain the byte array instead of BufferedImage soon.

Related

Problem clicking elements using class and index

I'm trying to write code to automatically DM people on Instagram. Im stuck on getting the code to click on the DM button.
In UIautomatorviewer, there is no text or a resource-id, so I tried using the class.
When I run the code it doesn't click on the right thing. It clicks on the button NEXT to it.
Here is the code -
By path2 = By.xpath("//android.widget.ImageView[#index='3']");
driver.findElement(path2).click();
Thread.sleep(5000);
Can anyone help? I'm new to this so i'm not very experienced.
Because I can not see the entire XML I can not really tell what you did wrong but probably your xpath is not correct.
With UIAutomatorViewer you can save the XML and then you can test your xpath on it. Either with XMLSpy or an online tool like https://www.freeformatter.com/xpath-tester.html.
Probably there are more android.widget.ImageView with index = 3 and I think appium selects the first one? So you could change your xpath to a more unique one like:
//android.widget.FrameLayout//android.widget.LinearLayout//android.widget.ImageView[#index='3']"
Based on UIAutomator Viewer screen you can also use content-desc as shown below
By path2 = By.xpath("//android.widget.ImageView[contains(#content-desc,'Message')]");
driver.findElement(path2).click();

Cannot go to "chrome://downloads/" in a newly opened tab with Selenium in Chrome

I am using Selenium and Java to write a test for Chrome browser. My problem is that somewhere in my test, I download something and it covers a web element. I need to close that download bar (I cannot scroll to the element). I searched a lot and narrowed down to this way to open the download page in a new tab:
((JavascriptExecutor) driver).executeScript("window.open('chrome://downloads/');");
It opens that new tab, but does not go to download page.
I also added this one:
driver.switchTo().window(tabs2.get(1));
driver.get("chrome://downloads/");
but it didn't work either.
I tried:
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL + "t");
and
action.sendKeys(Keys.CONTROL+ "j").build().perform();
action.keyUp(Keys.CONTROL).build().perform();
Thread.sleep(500);
but neither one even opened the tab.
It is because you can't open local resources programmatically.
Chrome raises an error:
Not allowed to load local resource: chrome://downloads/
Working solution is to run Chrome with following flags:
--disable-web-security --user-data-dir="C:\chrome_insecure"
But this trick doesn't work with Selenium Chrome Driver(I don't know actually why, a tried to remove all args that appears in chrome://version, but this doesn't helps).
So for me above solution is the only one that works:
C# example:
driver.Navigate().GoToUrl("chrome://downloads/")
There is another trick if you need to open downloaded file:
JavaScript example:
document.getElementsByTagName("downloads-manager")[0].shadowRoot.children["downloads-list"]._physicalItems[0].content.querySelectorAll("#file-link")[0].click()
Chrome uses Polymer and Shadow DOM so there is no easy way to query #file-link item.
Also you need to execute .click() method with JavaScript programatically because there is a custom event handler on it, which opens actual downloaded file instead of href attribute which point to url where you downloaded file from.
I started with this post and ended up with the solution given below. This one works in Chrome 71. First I highlighted the control and then clicked it.
The window object is actually the IWebDriver, the second method is called after the first one.
internal void NavigateToDownloads()
{
window.Navigate().GoToUrl("chrome://downloads/");
}
internal void OpenFirstDownloadLinkJS()
{
IJavaScriptExecutor js = (IJavaScriptExecutor) window;
js.ExecuteScript("document.getElementsByTagName('downloads-manager')[0].shadowRoot.children[4].children[0].children[1].shadowRoot.querySelectorAll('#content')[0].querySelector('#details > #title-area > #file-link').setAttribute('style', 'background: yellow;border: 2px solid red;');");
js.ExecuteScript("document.getElementsByTagName('downloads-manager')[0].shadowRoot.children[4].children[0].children[1].shadowRoot.querySelectorAll('#content')[0].querySelector('#details > #title-area > #file-link').click();");
}
Use this code (I wrote it in Python, but it should work in Java too with very slight modifications):
#switching to new window
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
#opening downloads
driver.get('chrome://downloads/')
#closing downloads:
driver.close()

How to make the screenshot of the entire display containing the browser using webdriver?

Does anybody know how to make full screenshot of display using webdriver?
In Selenium documentation I read that it is possible: (http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html)
..
The screenshot of the entire display containing the browser
..
I use Selenium Grid. My hub is on linux and node on windows. I tried to use Robot, however it takes screenshot on linux, however needs on windows
If you want a screenshot of your currently running browser instance then you can do it using following code:
public static void captureScreen(WebDriver driver, String screenshotFileName)
{
String screenshotsFile = screenshotsFolder+screenshotFileName+imageExtention;
try {
File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenShot, new File(screenshotsFile));
} catch (IOException e) {
}
}
But if you want to take screenshot of your active window (other than browser only) then you can use Robot class.
Edit:
Although it's too late for you, the link below contains your answer. I think it may be helpful for others who are searching for the same thing.
Screen shot issue in selenium webdriver
You need to use FirefoxDriver to screenshot whole page.
Chrome and IE doesn't support it.
hi try it like below it will take the complete webpage screen shot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in defined drive with name "screenshot.png"
FileUtils.copyFile(scrFile, new File("yourPath\\screenshot.png"));

While working with Selenium WebDriver and Java I am not able to use click() function of WebDriver (giving no exception)

I have set the following properties:-
Set environment variables JAVA_HOME,path,ANT_HOME,path (using JDK version --> jdk1.7.0_40)
In Eclipse set the system Library, added all needed jars and select all jars in Order and Export.
Install the Firefox Version 24 and used the Selenium jar(selenium-server-standalone-2.41.0).
Giving no error while running the Java application, also no exception while not able to click on particular element.
sendKeys(Keys.ENTER) is working fine, but instead I need to use click() method.
Also code is working fine on other systems, I think I am missing something.
click() method is not giving any valid response, it makes me feel like its only declared not defined. I have tried on different websites, on different elements and with different types(xpath, css selector, name, id) but nothing worked for me. I took focus on that element by webdriver and also by highlighting the element using javascript code, its showing that particular element is present. I have performed other operations like entering username after clicking on that element, its performing well. I have worked with different browsers, different webpages also maximize the window using selenium but no positive response.
Any help will appreciate.
Thanks in advance
Hi the snippet below worked fine for me
public static void main(String[]args){
WebDriver appDriver;
appDriver = new FirefoxDriver();
appDriver.get("https://web210.qa.drfirst.com/login.jsp");
WebElement loginButton = appDriver.findElement(By.className("btn"));
loginButton.click();
appDriver.switchTo().alert().accept();
appDriver.close();
}

How to capture Screenshot in Selenium Webdriver using Java without Window being resized [duplicate]

This question already has answers here:
How can I take a screenshot with Selenium WebDriver?
(48 answers)
Closed 6 years ago.
I am trying to take a screenshot of a webpage while selenium is running. I am using the following code for this purpose
WebDriver augmentedDriver = new Augmenter().augment(seleniumDriver);
File scrFile = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
Now it serves my purpose perfectly well except that whenever this method gets called the browser automatically gets into the default size and maximizes again.
And this continues every time the screenshot function gets called.
I am able to solve the problem If I am NOT using the selenium webdriver for taking the screenshots and using other java functions.
I wanted to know if anyone had similar problems/why I am having this problem. And is there any workaround?
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenshot.jpg"));
This code will definitely help
It tries to adapt to page size and take the screenshot as small as possible or as large as needed for the whole page to fit. Apart from being annoying, it should not be a cause of any other problems and is therefore considered a better solution than taking a screenshot of just the actual viewport which could be missing some important piece of the page you're trying to examine.
If you're not happy about it, use Robot and its createScreenCapture() method.
Or, but it will only work for Firefox, you may try overriding the FirefoxDriver's method for screenshots. Not tested, no idea whether you'll be allowed to do it or not.
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("FirefoxDriver.prototype.screenshot = function(a){};");
and (if that's not enough) maybe even
js.executeScript("FirefoxDriver.prototype.saveScreenshot = function(a,b){};");
Inferred from here. The actual screenshooting code is here. You can replace the FirefoxDriver.prototype.screenshot function with your own that wouldn't take the maximum scrollable values for height and width...
The code to take the screenshot make use of getScreenshotAs method of TakesScreenshot interface. Following code will take screenshot of the webpage opened by webDriver instance.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));
Now in order to take screenshot in case of test failure we will use AfterMethod annotation of TestNG. In the AfterMethod annotation we will use ITestResult interface's getStatus() method that returns the test result and in case of failure we can use the above commands to take screenshot. Code snippet to take screenshot on test failure-
#AfterMethod
public void takeScreenShotOnFailure(ITestResult testResult) throws IOException {
if (testResult.getStatus() == ITestResult.FAILURE) {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));
}
}
For complete sample script refer to http://artoftesting.com/automationTesting/screenShotInSelenium.html
I have created a method for this, which is very easy to use. It takes the screenshot of the whole web page. It counts and name the screen shot depending on the number of screenshots, the method also stores the screenshot as .png file into src.
public static void screenshot(WebDriver driver)
{
System.out.println("Taking the screenshot.");
console_logs("Taking the screenshot.");
scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("src//tempOutput//webPage_screenshot_"+count+".png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
//return scrFile;
}
Using the method:
screenshot(driver);

Categories

Resources