How to take partial screenshot (frame) with Selenium WebDriver?

后端 未结 5 1818
不思量自难忘°
不思量自难忘° 2020-12-05 01:06

Is it possible to take a screenshot with WebDriver of only one frame (not the complete window) within a frameset?

Alternatively, is it possible to define coordinate

5条回答
  •  广开言路
    2020-12-05 01:23

    Ruby solution

    Setup

    Install xvfb

    apt-get install xvfb -y
    

    Install headless browser and image manipulation gem

    gem install chunky_png
    gem install headless
    gem install selenium-webdriver
    

    Install chrome driver

    wget http://chromedriver.googlecode.com/files/chromedriver_linux64_.zip
    apt-get install unzip
    unzip chromedriver_linux64_.zip
    cp chromedriver /usr/local/bin
    

    More info can be found here

    Code

    #!/usr/bin/env ruby
    
    require "headless"
    require "selenium-webdriver"
    require 'chunky_png'
    
    headless = Headless.new
    headless.start
    
    site = "?_some_site_?"
    
    driver = Selenium::WebDriver.for :chrome
    driver.navigate.to site
    sleep 1
    driver.save_screenshot('screenshot.png')
    
    el= driver.find_element(:xpath, '?_some_xpath_?')
    
    image = ChunkyPNG::Image.from_file('screenshot.png')
    
    image.crop!(el.location.x + 1, el.location.y + 1, el.size.width, el.size.height)
    image.save('croped.png')
    
    driver.quit
    headless.destroy
    

提交回复
热议问题