4、截屏比较方便,使用browser.screenshot.save
# coding: gb2312
require 'watir-webdriver'
# 给String类增加一个编码转换的实例方法gb2312,即把字符串按gb2312编码,可避免Watir从网页提取中文字符时乱码
class String
def gb2312
self.encode("gb2312")
end
end
# 打开chrome driver
browser = Watir::Browser.new :chrome
begin
# 登陆QQ邮箱首页
browser.goto 'http://mail.qq.com'
# 输入邮箱账户
browser.text_field(:name,"uin").wait_until_present
browser.text_field(:name,"uin").send_keys("QQ账号")
# 输入密码
browser.text_field(:name, "p").wait_until_present
browser.text_field(:name, "p").send_keys("密码")
# 点击登陆
browser.input(:id, "btlogin").wait_until_present
browser.input(:id, "btlogin").click
# 选择写信
browser.a(:id,"composebtn").wait_until_present
browser.a(:id,"composebtn").click
# 输入收件人地址
browser.frame(:id,'mainFrame').input(:xpath,"//div[@id='toAreaCtrl']/div[@class='addr_text']/input").wait_until_present
browser.frame(:id,'mainFrame').input(:xpath,"//div[@id='toAreaCtrl']/div[@class='addr_text']/input").send_keys('收件人邮箱地址')
# 输入主题
browser.frame(:id,'mainFrame').input(:xpath, "//td[@class='content_title']/div/div/div/input[@id='subject']").wait_until_present
browser.frame(:id,'mainFrame').input(:xpath, "//td[@class='content_title']/div/div/div/input[@id='subject']").send_keys('新年快乐')
# 输入正文
browser.frame(:id,'mainFrame').iframe(:xpath, "//td[@class='qmEditorContent']/iframe").wait_until_present
browser.frame(:id,'mainFrame').iframe(:xpath, "//td[@class='qmEditorContent']/iframe").send_keys('恭喜发财')
# 选择附件
browser.frame(:id,'mainFrame').file_field(:name, 'UploadFile').set('C:/watir/qqmail.rb')
# 点击发送
browser.frame(:id,'mainFrame').a(:name, "sendbtn").wait_until_present
browser.frame(:id,'mainFrame').a(:name, "sendbtn").click
# 应该还可以采用更效率的方法以确定发送完成
sleep 60
# 确认发送结果, 如果与预期结果不一样就截屏保存下来
browser.frame(:id,'mainFrame').b(:id, "sendinfomsg").wait_until_present
acctual_send_result_info = browser.frame(:id,'mainFrame').b(:id, "sendinfomsg").text.gb2312
expect_send_result_info = "您的邮件已发送"
if acctual_send_result_info != expect_send_result_info
browser.screenshot.save('d:/qqmail.rb.error.png')
raise "点击发送后结果(#{acctual_send_result_info})不符合预期(#{expect_send_result_info})"
end
puts "发送成功"
rescue => error
puts "出现异常:#{error}"
ensure
browser.close if browser
end
下来慢慢总结Watir+Webdriver在WEB UI自动化方面的各种应用。