[英]Save page with css, js and images using watir
如何使用watir-webdriver保存頁面及其所有內容? browser.html
僅保存瀏覽器的元素。 如果我在轉儲browser.html
位置打開文件,則沒有樣式。
而且browser.html
不會保存iframe。 我可以遍歷iframe並將其分別保存,但是它們將與主頁分開。
我現在只記錄html,也許以后我會保存屏幕截圖,因為沒有簡單的方法來轉儲帶有CSS和圖像的整個頁面。
require 'fileutils'
class Recorder
attr_reader :request, :counter, :browser
# request should contain w(login_id start_time)
def initialize(request)
@request, @counter = request, 1
# Settings class contains my configs (enable recording, paths, etc.)
FileUtils.mkpath(path) if Settings.recorder.record and !File.exists?(path)
end
def record(hash)
return unless Settings.recorder.record
@browser = hash["browser"]
record_html(hash)
record_frames(hash)
@counter += 1
end
private
# hash should contain (method_name browser)
def record_html(hash)
File.open("#{path}#{generate_file_name(hash)}", "w") do |file|
file.write("<!--#{browser.url}-->\n")
file.write(browser.html)
end
end
def record_frames(hash)
browser.frames.each_with_index do |frame, index|
File.open("#{path}#{generate_file_name(hash, index + 1)}", "w") do |file|
file.write("<!--#{browser.url}-->\n")
file.write(frame.html)
end
end
end
def path
"#{Settings.recorder.path}/#{request["login_id"]}/#{request["start_time"]}/"
end
def generate_file_name(hash, frame=nil)
return "#{counter}-#{hash["method_name"]}.html" if frame.nil?
"#{counter}-frame#{frame}-#{hash["method_name"]}.html"
end
end
我不了解Watir,但對於那些可能想使用Selenium WebDriver(Watir環繞其周圍)保存頁面(包括直接在頁面中的CSS和JavaScript)的人來說,最簡單的方法是使用page_source方法( WebDriver類) 。 顧名思義,它提供了全部信息。 然后,只需將其保存到新文件即可,如下所示:
driver = Selenium::WebDriver.for(:firefox)
driver.get(URL_of_page_to_save)
file = File.new(filename, "w")
file.puts(driver.page_source)
file.close
但是,它不會將JavaScript或CSS保存在其他文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.