一尘不染

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

selenium

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

差不多完成了,但是我仍然坚持使用Selenium Webdriver获取element的屏幕截图。我是通过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#中实现相同的目的吗?


阅读 752

收藏
2020-06-26

共1个答案

一尘不染

在这里,我编写了一些代码以使用C#拍摄Element的屏幕截图

 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;
        }
    }

如果有任何问题,请通知我。

2020-06-26