如何在 Selenium 中将画布另存为 PNG?
我们可以在 Selenium 中将画布另存为 png。我们首先要借助任何定位器(如 xpath、css 等)来识别画布。然后使用 **getAttribute** 方法获取 src 属性值。
我们将在 Java 中使用 **URL** 类构建一个 URL,并通过 **ImageIO** 类获取一个 **BufferedImage**。然后使用同一个类,以 png 扩展形式将画布保存在某个位置。
让我们尝试将以下图像保存在项目文件夹中。
示例
代码实现。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; public class SaveCanvas{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://tutorialspoint.com/index.htm"); // identify canvas WebElement l = driver.findElement(By.xpath("//img[@title='Tutorialspoint']")); // get src value of element String v = l.getAttribute("src"); // creating URL URL i = new URL(v); //having BufferedImage with ImageIO class BufferedImage s = ImageIO.read(i); // save image in location with .png extension ImageIO.write(s, "png", new File("Logo.png")); driver.close(); } }
输出
Logo.png 文件已创建在项目文件夹中。
广告