我的小项目是用 Java 编写的,我需要用 C# 重写它.
I have my little project written on Java and I need to rewrite it in C#.
几乎完成了,但我一直坚持使用 Selenium webdriver 获取元素的屏幕截图.我用 Java 做的下一个方法:
It's almost done, but I am stuck on getting screenshot of element using Selenium webdriver. I did it in Java in the next way:
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# 重写它,因为我不太熟悉它.
It works perfect in Java, but I have no idea how to rewrite it in C#, as I am not so familiar with it.
有人可以提出一些在 C# 中实现相同目标的好方法吗?
Could someone suggest some nice way to achieve the same in C#?
这里我写了一些代码来用c#截取一个元素
Here i have written some code to take screenshot of an Element using 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;
}
}
如果有任何问题,请告诉我.
if any issue then let me know.
这篇关于如何在 C# 中使用 WebDriver 获取指定元素的屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!