2022年6月16日、宮崎にて
RubyでWebサイトのスクリーンショットを撮る
URLの一覧が書かれたファイルがあり、それぞれのページのスクリーンショットを撮りたい場合
https://github.com/mozilla/geckodriver/releasesからgeckodriverをインストールします。
geckodriver.exeがシステムのPATHに含まれている必要があります
watir-screenshot-stitch gemをインストールします
gem install watir-screenshot-stitch
コード
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
GitHub上のwatir-screenshot-stitch
追伸:RubyでWindowsプログラムのスクリーンショットを撮るためのgemもあります。
https://rubygems.org/gems/win32screenshot
これを拡張して、スクリーンショットをWord文書に追加することもできます。
https://rubywithwatir.blogspot.com/2008/07/how-do-i-take-screenshots-and-append-to.html
お読みいただきありがとうございます
この記事を気に入っていただけたら、
こちらのメールを送ってください。次に記事を書いたときにお知らせします。
Andi