Selenium保存元素图像

时间:2017-10-06 17:59:58

标签: c# selenium selenium-webdriver

当我使用webBrowser自动执行任务时,我保存图像的代码简洁明了:

    Image Getmg(WebBrowser webBrowser)
    {
        mshtml.HTMLWindow2 window = (mshtml.HTMLWindow2)webBrowser.Document.Window.DomWindow;
        window.execScript("var ctrlRange = document.body.createControlRange();ctrlRange.add(document.getElementById('captcha-image'));ctrlRange.execCommand('Copy');", "javascript");
        return Clipboard.GetImage();
    }

我只是在注入javascript。现在我正在使用SeleniumFireFox driver。我已经制作了保存图像的方法:

private void takeScreenshotOfElement(By elementToFind, string outputFileName) {
    //find element
    IWebElement my_image = driver.FindElement(elementToFind);

    //scrool to element
    Actions moveAction = new Actions(driver);
    moveAction.MoveToElement(my_image);
    moveAction.Perform();

    //take screenshot of full page
    ITakesScreenshot its = (ITakesScreenshot)driver;
    Screenshot screenShot = its.GetScreenshot();

    //convert screenShot to Bitmap
    var ms = new MemoryStream(screenShot.AsByteArray);
    Bitmap image = new Bitmap(Image.FromStream(ms));

    //get element size
    int imageWidth = my_image.Size.Width;
    int imageHeight = my_image.Size.Height;

    //get element position
    RemoteWebElement element = (RemoteWebElement)my_image;
    Point imagePosition = new Point();
    imagePosition.X = element.LocationOnScreenOnceScrolledIntoView.X;
    imagePosition.Y = element.LocationOnScreenOnceScrolledIntoView.Y;

    //crop screenShot
    Rectangle section = new Rectangle(imagePosition, new Size(imageWidth, imageHeight));
    Bitmap final_image = CropImage(image, section);

    //save element image
    final_image.Save(outputFileName);
}

基本上,当elementToFing位于浏览器顶部时,它正在工作。我也无法滚动到这个元素。当我看到elementToFind时,它没问题。但是当我看到这个元素时,我得到了:'System.InvalidOperationException' in WebDriver.dll。你知道怎么做吗?

要清楚,此代码无法正常运行:

//scroll to element
Actions moveAction = new Actions(driver);
moveAction.MoveToElement(my_image);
moveAction.Perform();

1 个答案:

答案 0 :(得分:2)

使用JavascriptExecutor滚动如下:

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", my_image);
Thread.sleep(500); 

来自Scroll Element into View with Selenium