如何通过Selenium捕获网页中WebElement的屏幕截图,而不是整个屏幕或页面的截图 [英] How to capture screenshot of a WebElement within a webpage but not the entire screen or page through Selenium
问题描述
我必须捕获特定网站的图像的屏幕截图.也许这是整个屏幕的20%折扣,我在下面的代码中使用过,它正在捕获整个屏幕.这无助于我解决问题.
I have to capture a screenshot of an image of a particular website. Maybe this is 20% off entire screen, I have used below code, it is capturing the entire screen. Which is not helping me to solve the problem.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
推荐答案
根据您的代码试用getScreenshotAs()
方法,将获取整个页面的屏幕截图.
As per your code trials getScreenshotAs()
method will take the screenshot of the entire page.
要捕获特定网页中 WebElement 的屏幕截图,可以使用 AShot()
方法导入 ashot-1.4.4.jar >,同时使用 Selenium Java Client v3.14.0 , ChromeDriver v2.41 , Chrome v 68.0 .
To capture the screenshot of an WebElement within a particular webpage you can use the AShot()
method importing ashot-1.4.4.jar while working with Selenium Java Client v3.14.0, ChromeDriver v2.41, Chrome v 68.0.
注意: ashot-1.4.4.jar 中的
AShot()
方法仅适用于因此,未启用 jQuery 的网站http://www.google.com/
ashot-1.4.4.jar 中的AShot()
方法不会能够拍摄所需的屏幕截图.So as the website
http://www.google.com/
is not jQuery enabledAShot()
method from ashot-1.4.4.jar won't be able to take the required screenshot.作为示例,我们将从网站
https://jquery.com/
拍摄快照.As an example we will take a snapshot from the website
https://jquery.com/
.
代码块:
Code Block:
package aShot; import java.io.File; import javax.imageio.ImageIO; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; public class ashot_google_homepage_logo { public static void main(String[] args) throws Exception { System.setProperty("god.bless.you", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); options.addArguments("disable-infobars"); options.addArguments("--disable-extensions"); WebDriver driver = new ChromeDriver(options); driver.get("https://jquery.com/"); WebElement myWebElement = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//h3[contains(.,'Lightweight Footprint')]"))); Screenshot myScreenshot = new AShot().takeScreenshot(driver, myWebElement); ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/elementScreenshot.png")); driver.quit(); } }
屏幕截图:
Screenshot:
您可以在如何获取屏幕截图中找到详细的讨论使用Selenium WebDriver
这篇关于如何通过Selenium捕获网页中WebElement的屏幕截图,而不是整个屏幕或页面的截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!