python + selenium 针对calculator测试 (练手)

这篇博客通过Python的Selenium库进行自动化测试,目标是打开Chrome浏览器,加载计算器网站,执行1+1运算并验证结果。若计算错误则进行截图保存。文章重点介绍了使用XPath进行元素定位以及异常处理技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这次练手的目标:

  1. Open Chrome浏览器.
  2. Launch Website
  3. 计算1 + 1 显示结果。做判断是否正确。
  4. 如失败,截图并保存

主要元素定位技术:
使用xpath定位,绝对定位://*[@id=”sciout”]/tbody/tr[2]/td[2]/div/div[3]/span[1]。
使用try …. except 异常捕获,抛出异常。

# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from _ast import Pass

calc = webdriver.Chrome()

# Launch website
calc.get("http://www.calculator.net/")
#Maximize the brower
calc.maximize_window()
# The initialization value
one = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[3]/span[1]')
two = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[3]/span[2]')
three = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[3]/span[3]')
add = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[1]/span[4]')
sum1 = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[5]/span[4]')
MR = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[4]/span[5]')
MC = calc.find_element_by_xpath('//*[@id="sciout"]/tbody/tr[2]/td[2]/div/div[5]/span[5]')
resul = calc.find_element_by_id("sciOutPut")

def result(es, res, casename):
    if es == res:
         print  "PASS"
    else:
        print  "FAIL"
        calc.get_screenshot_as_file("F:\calc\\%s.png"  %casename)
        print  "F:\calc\\%s.png"  %casename

# test main
casename = "casename1"
try:
    one.click()
    add.click()
    two.click()
    sum1.click()
    res = resul.text
    time.sleep(2)
    result(3, res, casename)
    MR.click()
    time.sleep(5)
    calc.quit()
except Exception, e:
    print e
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值