gpt4 book ai didi

java - 如何在 C# 中使用 WebDriver 获取指定元素的屏幕截图

转载 作者:行者123 更新时间:2023-12-05 08:42:59 25 4
gpt4 key购买 nike

我有一个用 Java 编写的小项目,我需要用 C# 重写它。

它几乎完成了,但我仍然坚持使用 Selenium webdriver 获取元素的屏幕截图。我用 Java 用下一种方式做到了:

    public String saveImage(){
String src = "";
try{
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
Point point = elementToScreent.getLocation();
int eleWidth = elementToScreent.getSize().getWidth();
int eleHeight = elementToScreent.getSize().getHeight();
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth,
eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
src = path + System.currentTimeMillis() +".png";
FileUtils.copyFile(screenshot, new File(src));
}catch(Exception e){
e.printstacktrace();
}
return src;
}

它在 Java 中运行完美,但我不知道如何在 C# 中重写它,因为我不太熟悉它。

有人可以建议一些在 C# 中实现相同目的的好方法吗?

最佳答案

在这里,我编写了一些代码,使用 C# 截取元素

 FirefoxDriver driver = null;
private WebDriverWait wait;

// Use this function to take screenshot of an element.

public static Bitmap GetElementScreenShot(IWebDriver driver, IWebElement element)
{
Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
var img = Image.FromStream(new MemoryStream(sc.AsByteArray)) as Bitmap;
return img.Clone(new Rectangle(element.Location, element.Size), img.PixelFormat);
}
//testing function
public void GetIPLocation(string IPAddress)
{
try
{
if (driver == null)
driver = new FirefoxDriver();
if (driver.Title != "IP Location Finder - Geolocation")
driver.Navigate().GoToUrl("https://www.iplocation.net/");
if (wait == null)
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
var ipTextBox = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("input[type='text']")));

ipTextBox.Clear();
ipTextBox.SendKeys(IPAddress);
wait.Until(ExpectedConditions.ElementExists(By.CssSelector("input[type='submit']"))).Click();

foreach (IWebElement element in driver.FindElements(By.CssSelector("div>.col.col_12_of_12")))
{
if (element.FindElements(By.TagName("h4")).Count > 0)
{
var img = GetElementScreenShot(driver, element);
img.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
}
catch (Exception)
{

throw;
}
}

如果有任何问题,请告诉我。

关于java - 如何在 C# 中使用 WebDriver 获取指定元素的屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35921168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com