【问题标题】:How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?如何使用 Selenium Webdriver 捕获特定元素而不是整个页面的屏幕截图?
【发布时间】:2012-11-29 17:14:10
【问题描述】:

目前我正在尝试使用 Selenium WebDriver 捕获屏幕截图。但我只能获得整个页面的屏幕截图。但是,我想要的只是捕获页面的一部分,或者可能只是基于 ID 或任何特定元素定位器的特定元素。 (比如我想抓到image id = "Butterfly"的图片)

有什么方法可以按选定的项目或元素截取屏幕截图吗?

【问题讨论】:

  • AFAIK,该功能仅用于捕获整个页面。我们没有将元素 id 或名称作为输入的屏幕截图功能。
  • 谁能告诉我c#中BUfferedImage的方法调用是什么?我找不到与此相关的任何类似方法。

标签: selenium selenium-webdriver screenshot


【解决方案1】:

我们可以通过裁剪整个页面截图来获取元素截图,如下所示:

driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("hplogo"));

// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage  fullImg = ImageIO.read(screenshot);

// Get the location of element on the page
Point point = ele.getLocation();

// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();

// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
    eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);

// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);

【讨论】:

  • 感谢您的回复。但是,为什么我的 webdriver 和你的不一样。它使用了 IWebDriver,ItakeScreenshot 并且没有 OutputType.FILE 和 BufferedImage... 我使用的是过时版本的 webdriver selenium 吗?
  • 你在使用 C# webdriver 绑定吗?
  • 是的,我想是的。以前我用的是 RC,最近我只是改用网络驱动程序。
  • 此实现用于 Java 绑定。这个概念也适用于 C#。但我不太了解 C# 语言。您需要使用 C# 等效库(BufferedImage、ImageIO...)
  • 以上代码在 Chrome 中不起作用。异常 java.awt.image.RasterFormatException: (y + height) is outside of Raster 在 BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
【解决方案2】:

这是一个使用 Selenium webdriver 和 Pillow 的 Python 3 版本。 该程序捕获整个页面的屏幕截图并根据其位置裁剪元素。元素图像将以 image.png 的形式提供。 Firefox 支持直接使用 element.screenshot_as_png('image_name') 保存元素图像。

from selenium import webdriver
from PIL import Image

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

element = driver.find_element_by_id("lst-ib")

location = element.location
size = element.size

driver.save_screenshot("shot.png")

x = location['x']
y = location['y']
w = size['width']
h = size['height']
width = x + w
height = y + h

im = Image.open('shot.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('image.png')

更新

现在 chrome 还支持单个元素的屏幕截图。所以你可以直接截取下面给出的网页元素的截图。

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')
image = driver.find_element_by_id("lst-ib").screenshot_as_png 
# or
# element = driver.find_element_by_id("lst-ib")
# element.screenshot_as_png("image.png")

【讨论】:

  • 我很确定element.size 以点为单位,而driver.save_screenshot 生成的屏幕截图具有像素尺寸。如果您的屏幕像素与点的比率不是 1(例如,视网膜 MacBook 的每个点有两个像素 - 比率为 2),那么您需要将 wh 乘以该比率。
  • 新版本已经可以使用element.screenshot('elemenent.png'),看@rovr138的回答
  • 我试过这样并给了我 typeError。 'bytes' 对象不可调用
  • @puppet 对于内存加载执行此操作。 from StringIO import StringIO; from PIL import Image; img = Image.open(StringIO(image))
  • 我遇到了与@puppet 类似的问题。这对我有用:import io; from PIL import Image; img = Image.open(io.BytesIO(image)); img.save("image.png")
【解决方案3】:

Yandex 的 AShot 框架可用于在 Selenium WebDriver 脚本中截屏

  • 完整的网页
  • 网页元素

这个框架可以在https://github.com/yandex-qatools/ashot找到。

截图的代码非常简单:

整页

Screenshot screenshot = new AShot()
        .shootingStrategy(new ViewportPastingStrategy(1000))
        .takeScreenshot(driver);

ImageIO.write(screenshot.getImage(), "PNG", new File("c:\\temp\\results.png"));

特定的网络元素

Screenshot screenshot = new AShot()
        .takeScreenshot(driver, driver.findElement(By.xpath("(//div[@id='ct_search'])[1]")));
    
ImageIO.write(screenshot.getImage(), "PNG", new File("c:\\temp\\div_element.png"));

this article 上查看更多详细信息和更多代码示例。

【讨论】:

  • 注意你可能还需要.shootingStrategy(ShootingStrategies.viewportPasting(100)) SPECIFIC WEB ELEMENT 模式,否则它可能无法捕获所有元素。
【解决方案4】:

Node.js 中,我编写了以下代码,但它不是基于selenium 的官方WebDriverJS,而是基于SauceLabs's WebDriverWD.js 和一个非常紧凑的图像库EasyImage

我只是想强调一下,你不能真正截取一个元素,但你应该首先截取整个页面的截图,然后选择你喜欢的页面部分并裁剪该特定部分:

browser.get(URL_TO_VISIT)
       .waitForElementById(dependentElementId, webdriver.asserters.isDisplayed, 3000)
       .elementById(elementID)
        .getSize().then(function(size) {
            browser.elementById(elementID)
                   .getLocation().then(function(location) {
                        browser.takeScreenshot().then(function(data) {
                            var base64Data = data.replace(/^data:image\/png;base64,/, "");
                            fs.writeFile(filePath, base64Data, 'base64', function(err) {
                                if (err) {
                                    console.log(err);
                                } 
                                else {
                                    cropInFile(size, location, filePath);
                                }
                                doneCallback();
                        });
                    });
                });
            }); 

cropInFileFunction 是这样的:

var cropInFile = function(size, location, srcFile) {
    easyimg.crop({
            src: srcFile,
            dst: srcFile,
            cropwidth: size.width,
            cropheight: size.height,
            x: location.x,
            y: location.y,
            gravity: 'North-West'
        },
        function(err, stdout, stderr) {
            if (err) throw err;
        });
};

【讨论】:

  • 您的 EasyImage 库已损坏:“ImageMagickMissingError”
【解决方案5】:

对于所有需要 C# 代码的人,下面是我的实现的简化版本。

public static void TakeScreenshot(IWebDriver driver, IWebElement element)
{
    try
    {
        string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
        Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
        System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
        System.Drawing.Rectangle croppedImage = new System.Drawing.Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
        screenshot = screenshot.Clone(croppedImage, screenshot.PixelFormat);
        screenshot.Save(String.Format(@"C:\SeleniumScreenshots\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg));
    }
    catch (Exception e)
    {
        logger.Error(e.StackTrace + ' ' + e.Message);
    }
}

【讨论】:

  • 谢谢。这很有帮助,而且中肯而完美。
【解决方案6】:

我在截图上浪费了很多时间,我想保存你的。 我使用了 chrome + selenium + c#,结果非常糟糕。最后我写了一个函数:

driver.Manage().Window.Maximize();
             RemoteWebElement remElement = (RemoteWebElement)driver.FindElement(By.Id("submit-button")); 
             Point location = remElement.LocationOnScreenOnceScrolledIntoView;  

             int viewportWidth = Convert.ToInt32(((IJavaScriptExecutor)driver).ExecuteScript("return document.documentElement.clientWidth"));
             int viewportHeight = Convert.ToInt32(((IJavaScriptExecutor)driver).ExecuteScript("return document.documentElement.clientHeight"));

             driver.SwitchTo();

             int elementLocation_X = location.X;
             int elementLocation_Y = location.Y;

             IWebElement img = driver.FindElement(By.Id("submit-button"));

             int elementSize_Width = img.Size.Width;
             int elementSize_Height = img.Size.Height;

             Size s = new Size();
             s.Width = driver.Manage().Window.Size.Width;
             s.Height = driver.Manage().Window.Size.Height;

             Bitmap bitmap = new Bitmap(s.Width, s.Height);
             Graphics graphics = Graphics.FromImage(bitmap as Image);
             graphics.CopyFromScreen(0, 0, 0, 0, s);

             bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);

             RectangleF part = new RectangleF(elementLocation_X, elementLocation_Y + (s.Height - viewportHeight), elementSize_Width, elementSize_Height);

             Bitmap bmpobj = (Bitmap)Image.FromFile(filePath);
             Bitmap bn = bmpobj.Clone(part, bmpobj.PixelFormat);
             bn.Save(finalPictureFilePath, System.Drawing.Imaging.ImageFormat.Png); 

【讨论】:

  • 只要您尝试捕获不滚动即可看到的元素,它就可以正常工作。当您需要滚动到某个元素以捕获它时,y 偏移量从页面顶部开始计算,然后超出全屏图像的边界。所以最简单的解决方案是要么增加屏幕尺寸代码 this.driver.manage().window().setSize(new Dimension(1680, 1050));或通过 css 删除任何不需要的元素。正确的解决方案是计算滚动的 y 偏移量。
【解决方案7】:

Surya's answer 如果您不介意涉及磁盘 IO,则效果很好。如果您不想这样做,那么这种方法可能更适合您

private Image getScreenshot(final WebDriver d, final WebElement e) throws IOException {
    final BufferedImage img;
    final Point topleft;
    final Point bottomright;

    final byte[] screengrab;
    screengrab = ((TakesScreenshot) d).getScreenshotAs(OutputType.BYTES);

    img = ImageIO.read(new ByteArrayInputStream(screengrab));

    //crop the image to focus on e
    //get dimensions (crop points)
    topleft = e.getLocation();
    bottomright = new Point(e.getSize().getWidth(),
                            e.getSize().getHeight());

    return img.getSubimage(topleft.getX(),
                           topleft.getY(),
                           bottomright.getX(),
                           bottomright.getY());
}

如果您愿意,可以跳过声明 screengrab 而改为执行

img = ImageIO.read(
    new ByteArrayInputStream(
        ((TakesScreenshot) d).getScreenshotAs(OutputType.BYTES)));

这更干净,但为了清楚起见,我把它留了下来。然后你可以save it as a fileput it in a JPanel 尽情享受。

【讨论】:

    【解决方案8】:

    Python 3

    用 Selenium 3.141.0 和 chromedriver 73.0.3683.68 试过,这行得通,

    from selenium import webdriver
    
    chromedriver = '/usr/local/bin/chromedriver'
    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument('window-size=1366x768')
    chromeOptions.add_argument('disable-extensions')
    cdriver = webdriver.Chrome(options=chromeOptions, executable_path=chromedriver)
    
    cdriver.get('url')
    element = cdriver.find_element_by_css_selector('.some-css.selector')
    
    element.screenshot_as_png('elemenent.png')
    

    无需获取完整图像并获取全屏图像的一部分。

    这可能在创建 Rohit's answer 时不可用。

    【讨论】:

      【解决方案9】:

      我认为这里的大多数答案都是过度设计的。我这样做的方式是通过 2 个辅助方法,第一个等待基于任何选择器的元素;第二个截图。

      注意:我们将WebElement 转换为TakesScreenshot 实例,因此我们只专门捕获图像中的那个元素。如果你想要完整的页面/窗口,你应该转换driver

      编辑:我忘了说我使用的是 Java 和 Selenium v​​3(但对于 v4 应该是一样的)

      WebDriver driver = new FirefoxDriver(); // define this somewhere (or chrome etc)
      
      public <T> T screenshotOf(By by, long timeout, OutputType<T> type) {
          return ((TakesScreenshot) waitForElement(by, timeout))
                  .getScreenshotAs(type);
      }
      
      public WebElement waitForElement(By by, long timeout) {
          return new WebDriverWait(driver, timeout)
                  .until(driver -> driver.findElement(by));
      }
      

      然后像这样截图你想要的任何东西:

      long timeout = 5;   // in seconds
      /* Screenshot (to file) based on first occurence of tag */
      File sc = screenshotOf(By.tagName("body"), timeout, OutputType.FILE); 
      /* Screenshot (in memory) based on CSS selector (e.g. first image in body
      who's "src" attribute starts with "https")  */
      byte[] sc = screenshotOf(By.cssSelector("body > img[href^='https']"), timeout, OutputType.BYTES);
      

      【讨论】:

        【解决方案10】:
        public void GenerateSnapshot(string url, string selector, string filePath)
            {
                using (IWebDriver driver = new ChromeDriver())
                {
                    driver.Navigate().GoToUrl(url);
                    var remElement = driver.FindElement(By.CssSelector(selector));
                    Point location = remElement.Location;
        
                    var screenshot = (driver as ChromeDriver).GetScreenshot();
                    using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
                    {
                        using (Bitmap bitmap = new Bitmap(stream))
                        {
                            RectangleF part = new RectangleF(location.X, location.Y, remElement.Size.Width, remElement.Size.Height);
                            using (Bitmap bn = bitmap.Clone(part, bitmap.PixelFormat))
                            {
                                bn.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
                            }
                        }
                    }
                    driver.Close();
                }
            }
        

        【讨论】:

          【解决方案11】:

          如果您正在寻找 JavaScript 解决方案,这是我的要点:

          https://gist.github.com/sillicon/4abcd9079a7d29cbb53ebee547b55fba

          基本思路是一样的,先截屏,再裁剪。 但是,我的解决方案不需要其他库,只需要纯 WebDriver API 代码。但是,副作用是它可能会增加测试浏览器的负载。

          【讨论】:

          • 请将代码粘贴到您的答案中,而不是链接到其他来源
          【解决方案12】:

          这是一个 C# 的扩展函数:

          public static BitmapImage GetElementImage(this IWebDriver webDriver, By by)
          {
              var elements = webDriver.FindElements(by);
              if (elements.Count == 0)
                  return null;
          
              var element = elements[0];
              var screenShot = (webDriver as ITakesScreenshot).GetScreenshot();
              using (var ms = new MemoryStream(screenShot.AsByteArray))
              {
                  Bitmap screenBitmap;
                  screenBitmap = new Bitmap(ms);
                  return screenBitmap.Clone(
                      new Rectangle(
                          element.Location.X,
                          element.Location.Y,
                          element.Size.Width,
                          element.Size.Height
                      ),
                      screenBitmap.PixelFormat
                  ).ToBitmapImage();
              }
          }
          

          现在您可以使用它来拍摄任何元素的图像,如下所示:

          var image = webDriver.GetElementImage(By.Id("someId"));
          

          【讨论】:

            【解决方案13】:

            考虑使用 needle - 用于自动视觉比较的工具 https://github.com/bfirsh/needle , 它具有内置功能,允许截取特定元素的屏幕截图(由 CSS 选择器选择)。该工具适用于 Selenium 的 WebDriver,它是用 Python 编写的。

            【讨论】:

              【解决方案14】:

              在 Selenium 中为特定元素拍摄快照的函数下方。这里的驱动程序是一种WebDriver。

              private static void getScreenshot(final WebElement e, String fileName) throws IOException {
                final BufferedImage img;
                final Point topleft;
                final Point bottomright;
                final byte[] screengrab;
                screengrab = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                img = ImageIO.read(new ByteArrayInputStream(screengrab));
                topleft = e.getLocation();
                bottomright = new Point(e.getSize().getWidth(), e.getSize().getHeight());
                BufferedImage imgScreenshot= 
                    (BufferedImage)img.getSubimage(topleft.getX(), topleft.getY(), bottomright.getX(), bottomright.getY());
                File screenshotLocation = new File("Images/"+fileName +".png");    
                ImageIO.write(imgScreenshot, "png", screenshotLocation);
               }
              

              【讨论】:

              【解决方案15】:

              c#代码:

              public Bitmap MakeElemScreenshot( IWebDriver driver, WebElement elem)
              {
                  Screenshot myScreenShot = ((ITakesScreenshot)driver).GetScreenshot();
              
                  Bitmap screen = new Bitmap(new MemoryStream(myScreenShot.AsByteArray));
                  Bitmap elemScreenshot = screen.Clone(new Rectangle(elem.Location, elem.Size), screen.PixelFormat);
              
                  screen.Dispose();
              
                  return elemScreenshot;
              }
              

              【讨论】:

                【解决方案16】:
                using System.Drawing;
                using System.Drawing.Imaging;
                using OpenQA.Selenium;
                using OpenQA.Selenium.Firefox;
                
                public void ScreenshotByElement()
                {
                    IWebDriver driver = new FirefoxDriver();
                    String baseURL = "www.google.com/"; //url link
                    String filePath = @"c:\\img1.png";      
                
                    driver.Navigate().GoToUrl(baseURL);
                    var remElement = driver.FindElement(By.Id("Butterfly"));
                    Point location = remElement.Location;
                
                    var screenshot = (driver as FirefoxDriver).GetScreenshot();
                    using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
                    {
                        using (Bitmap bitmap = new Bitmap(stream))
                        {
                            RectangleF part = new RectangleF(location.X, location.Y, remElement.Size.Width, remElement.Size.Height);
                            using (Bitmap bn = bitmap.Clone(part, bitmap.PixelFormat))
                            {
                                bn.Save(filePath, ImageFormat.Png);                        
                            }
                        }
                    }
                }
                

                【讨论】:

                  【解决方案17】:

                  如果您在 chrome 中遇到异常 java.awt.image.RasterFormatException,或者您想将元素滚动到视图中,然后捕获屏幕截图。

                  这是来自@Surya 答案的解决方案。

                          JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
                          Long offsetTop = (Long) jsExecutor.executeScript("window.scroll(0, document.querySelector(\""+cssSelector+"\").offsetTop - 0); return document.querySelector(\""+cssSelector+"\").getBoundingClientRect().top;");
                  
                          WebElement ele = driver.findElement(By.cssSelector(cssSelector));
                  
                          // Get entire page screenshot
                          File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                          BufferedImage  fullImg = ImageIO.read(screenshot);
                  
                          // Get the location of element on the page
                          Point point = ele.getLocation();
                  
                          // Get width and height of the element
                          int eleWidth = ele.getSize().getWidth();
                          int eleHeight = ele.getSize().getHeight();
                  
                          // Crop the entire page screenshot to get only element screenshot
                          BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), Math.toIntExact(offsetTop),
                                  eleWidth, eleHeight);
                          ImageIO.write(eleScreenshot, "png", screenshot);
                  
                          // Copy the element screenshot to disk
                          File screenshotLocation = new File("c:\\temp\\div_element_1.png");
                          FileUtils.copyFile(screenshot, screenshotLocation);
                  

                  【讨论】:

                  • 我正在使用 selenium-java-2.53.1,编译组:'org.seleniumhq.selenium',名称:'selenium-java',版本:'2.53.1',chrome-web-驱动程序,我正在尝试从网页resident.uidai.gov.in/offlineaadhaar 裁剪 By.xpath(".//img[@class= 'captcha']"),但是您的代码无法正常工作。它裁剪了页面的一些错误部分。你能帮我裁剪验证码吗?
                  【解决方案18】:

                  这是我的版本,使用 C#

                  public static byte[] GetElementImage(this IWebElement element)
                      {
                          var screenShot = MobileDriver.Driver.GetScreenshot();
                          using (var stream = new MemoryStream(screenShot.AsByteArray))
                          {
                              var screenBitmap = new Bitmap(stream);
                              var elementBitmap = screenBitmap.Clone(
                                  new Rectangle(
                                      element.Location.X,
                                      element.Location.Y,
                                      element.Size.Width,
                                      element.Size.Height
                                  ),
                                  screenBitmap.PixelFormat
                              );
                              var converter = new ImageConverter();
                              return (byte[]) converter.ConvertTo(elementBitmap, typeof(byte[]));
                          }
                      }
                  

                  【讨论】:

                    【解决方案19】:

                    要截取特定元素的屏幕截图,您现在可以使用以下命令:

                    public void takeCanvasScreenshot(WebElement element, String imageName) {
                       
                       File screenshot = element.getScreenshotAs(OutputType.FILE);
                    
                       try {
                           FileUtils.copyFile(screenshot, new File("src/main/resources/screenshots/" + imageName + ".png"));
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                    }
                    

                    【讨论】:

                      【解决方案20】:

                      对于 C#,下面的代码可以工作。

                      试试
                      {

                      IWebElement transactions = driver.FindElement(By.XPath(".//*[@id='some element']"));

                      Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();

                      string title = "某个标题";

                      screenshot.SaveAsFile(title, ScreenshotImageFormat.Jpeg);

                      } 捕捉(例外) {

                      // 未找到元素时处理

                      }

                      【讨论】:

                        【解决方案21】:

                        我正在使用@Brook 答案的修改版本,即使对于需要滚动页面的元素也能正常工作。

                        public void TakeScreenshot(string fileNameWithoutExtension, IWebElement element)
                        {
                            // Scroll to the element if necessary
                            var actions = new Actions(_driver);
                            actions.MoveToElement(element);
                            actions.Perform();
                            // Get the element position (scroll-aware)
                            var locationWhenScrolled = ((RemoteWebElement) element).LocationOnScreenOnceScrolledIntoView;
                            var fileName = fileNameWithoutExtension + ".png";
                            var byteArray = ((ITakesScreenshot) _driver).GetScreenshot().AsByteArray;
                            using (var screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray)))
                            {
                                var location = locationWhenScrolled;
                                // Fix location if necessary to avoid OutOfMemory Exception
                                if (location.X + element.Size.Width > screenshot.Width)
                                {
                                    location.X = screenshot.Width - element.Size.Width;
                                }
                                if (location.Y + element.Size.Height > screenshot.Height)
                                {
                                    location.Y = screenshot.Height - element.Size.Height;
                                }
                                // Crop the screenshot
                                var croppedImage = new System.Drawing.Rectangle(location.X, location.Y, element.Size.Width, element.Size.Height);
                                using (var clone = screenshot.Clone(croppedImage, screenshot.PixelFormat))
                                {
                                    clone.Save(fileName, ImageFormat.Png);
                                }
                            }
                        }
                        

                        两个ifs 是必需的(至少对于 chrome 驱动程序而言),因为在需要滚动时,裁剪的大小超过了屏幕截图大小的 1 个像素。

                        【讨论】:

                        • 我在尝试您的方法时收到此错误:无法将透明代理转换为类型“OpenQA.Selenium.Remote.RemoteWebElement”
                        • 我是专门用Chrome驱动的,你用的是哪个驱动?
                        • 我也在使用 ChromeDriver。我的测试使用的是 IWebElements,我们遵循 OpenQA.Selenium.Support nuget 包中的 PageFactory 方法。
                        【解决方案22】:

                        我相信这对您不起作用,因为您使用 C#,而且我的解决方案包括一个 Java 库,但也许其他人会发现它有帮助。

                        要捕获自定义屏幕截图,您可以使用 Shutterbug 库。为此目的的具体要求是:

                        Shutterbug.shootElement(driver, element).save();
                        

                        【讨论】:

                          【解决方案23】:

                          我遵循了来自@codeslord 的示例代码,但由于某种原因,我不得不以不同的方式访问我的屏幕截图数据:

                           # Open the Firefox webdriver
                           driver = webdriver.Firefox()
                           # Find the element that you're interested in
                           imagepanel = driver.find_element_by_class_name("panel-height-helper")
                           # Access the data bytes for the web element
                           datatowrite = imagepanel.screenshot_as_png
                           # Write the byte data to a file
                           outfile = open("imagepanel.png", "wb")
                           outfile.write(datatowrite)
                           outfile.close()
                          

                          (使用 Python 3.7、Selenium 3.141.0 和 Mozilla Geckodriver 71.0.0.7222)

                          【讨论】:

                            猜你喜欢
                            • 2023-01-23
                            • 2021-05-07
                            • 2012-10-26
                            • 2019-01-31
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            相关资源
                            最近更新 更多