Miyazaki, 16 giugno 2022
Fare screenshot di siti web con Ruby
Avete un file con un elenco di URL e volete fare uno screenshot di ciascuno.
Installate geckodriver da https://github.com/mozilla/geckodriver/releases
geckodriver.exe deve trovarsi nel PATH di sistema
Installate la gem watir-screenshot-stitch
gem install watir-screenshot-stitch
Codice
require 'URI'
require 'fileutils'
require 'watir-screenshot-stitch'
basepath = File.join(__dir__, 'screenshots')
FileUtils.mkdir_p basepath
content = File.read('20220610_URLS.txt')
b = Watir::Browser.new :firefox
content.lines.each do |line|
line = line.strip
begin
if line.include?("http")
uri = URI.parse(line).normalize.to_s
hostname = URI.parse(line).host
path = File.join(basepath, hostname)
FileUtils.mkdir_p path
puts uri
b.goto uri
png = b.screenshot.base64_geckodriver
filename = uri.gsub(/[^0-9A-Za-z.\-]/, '_')
path = File.join(path, "#{filename}.png")
File.open(path, 'wb') { |f| f.write(Base64.decode64(png)) }
end
rescue
# puts line + " is not url"
end
end
watir-screenshot-stitch su GitHub
PS: esiste anche una gem per fare screenshot di programmi Windows in Ruby:
https://rubygems.org/gems/win32screenshot
Si potrebbe estendere il codice per aggiungere gli screenshot a documenti Word:
https://rubywithwatir.blogspot.com/2008/07/how-do-i-take-screenshots-and-append-to.html
Grazie per la lettura
Se l’articolo vi è piaciuto,
inviate semplicemente questa e-mail. Vi avviserò la prossima volta che scrivo qualcosa.
Andi