你需要知道的有关Selenium异常处理的都在这儿

你需要知道的有关Selenium异常处理的都在这儿,第1张

什么是异常

顾名思义,作为程序员的一种常用术语,“异常”与任何特定的编程语言无关。它属于程序因为突然中止,而未能交付出预期输出的事件。通常,引发异常出现的潜在因素往往来自如下方面:

· Java虚拟内存(JVM)的不足

· 请求访问的文件在目标系统中不存在

· 用户提供了无效的数据

· 在正常的通信过程中突然出现断网

Java中的异常类型

1 已查明的异常(Checked Exceptions):编译器在编译的过程中,会检查到这些异常,并验证它们是否已被处理。如果未被处理,系统会报告编译错误。因此它们被通称为编译时异常(compile-time exceptions)。下面是一些常见的此类异常示例:

· SQLException:程序在基于 SQL 语法执行 数据库 查询时,可能会产生此类异常。

· IOException:程序在文件上执行无效的I/O流 *** 作时,可能会产生此类异常。

· ClassNotFoundException:当JVM无法找到所需的Java类时,可能会产生此类异常。

2 未查明的异常(Unchecked Exceptions):这些异常是在程序的执行期间发生的逻辑错误,因此通常称为运行时异常(Runtime Exceptions)。此类异常在编译时未被检查出来,或者在整个编译过程中已被忽略。下面是一些典型的此类异常示例:

· NullPointerException:当访问具有空值的对象时,可能会产生此类异常。

· ArrayIndexOutofBound:当使用无效的索引值去访问数组时,可能会产生此类异常。

· IllegalArgumentException:当程序将不正确的参数传递给方法时,可能会产生此类异常。

· NumberFormatException:当程序将字符串传递给无法转换为数字的方法时,可能会产生此类异常。

· ArithmeticException:当程序执行不正确的算术运算(例如将数字除以零)时,可能会产生此类异常。

异常处理标准

通过对异常处理能力的提升,我们不仅可以保持代码的整洁,而且能够增强其可维护性、可扩展性和可阅读性。当然,不同的面向对象编程(Object-Oriented Programming,OOP)语言,具有不同的异常处理方法。以下是一些常用的Java异常处理标准:

Try-Catch:该关键字组合可被用于捕获异常。其中,try块应当被放在开头,而catch块应被放在try块的末尾,以便捕获异常,并采取必要的行动。也就是说,我们可以在遇到异常时,创建异常类的对象,以便使用以下预定义的方法,来显示调试信息:

· printStackTrace():该函数可用于打印栈的跟踪、异常的名称、以及其他重要的异常信息。

· getMessage():此函数有助于获取针对异常的深入描述。

try

{

// Code

} catch(Exception e){

// Code for Handling exception

}

同时,Try-Catch块也可以用其他高级方法来处理异常,例如,我们可能希望从单个代码块中捕获多个异常,那么就可以通过在try块之后的多个catch块,去处理不同的异常。而且,我们在try块之后,使用无限数量的catch块。

try

{

//Code

} catch(ExceptionType1 e1){

//Code for Handling Exception 1

} catch(ExceptionType2 e2){

//Code for Handling Exception 2

}

Throw/Throws:如果程序员想显式地抛出异常,那么可以使用throw关键字,与要在运行时处理的异常对象协同使用。

public static void exceptionProgram()throws Exception{

try {

// write your code here

} Catch(Exception b){

// Throw an Exception explicitly

throw(b); }

}

如果开发者想抛出多个异常,则可以通过在方法签名的子句中使用throws关键字来抛出,并且由方法的调用者去进行异常处理。

public static void exceptionProgram()throws ExceptionType1, ExceptionType2{

try {

// write your code here

} catch(ExceptionType1 e1){

// Code to handle exception 1

} catch(ExceptionType1 e2){

// Code to handle exception 2

}

finally:该个代码块往往是在try-catch块之后被创建的。也就是说,无论是否抛出异常,它都会被执行。

try {

//Code

} catch(ExceptionType1 e1){

//Catch block

} catch(ExceptionType2 e2){

//Catch block

} finally {

//The finally block always executes

}

Selenium中的常见异常

WebDriverException定义了Selenium中的多种异常,我们从中选取最常见的异常予以介绍,并配上简单的针对Selenium的异常处理方案:

1 NoSuchElementException

当WebDriver无法定位所需要元素时,Selenium可能会产生此类异常。此处的NoSuchElementException是NotFoundException类的子类,它通常出现在程序使用了无效的定位器时。

此外,如果WebDriver仍然停留在上一页、或正在加载下一页,而所需的定位器已到达了下一页时,就会因为该延迟而出现异常。为此,我们应当通过适当的等待处理 测试 ,最大限度地减少此类异常的发生。

当然,此类异常可以在catch块中被捕获到,并且可以在其中执行所需的 *** 作,以继续完成自动化的测试。例如:

try { driverfindElement(Byid("form-save"))click(); } catch(NoSuchElementException e){

Systemoutprintln(“WebDriver couldn’t locate the element”); }

2 NoSuchWindowException

该异常也是NotFoundException类的子类。如果WebDriver尝试着切换到无效的 浏览器 窗口,那么WebDriver将抛出NoSuchWindowException。因此,要实现窗口切换的好方法是,首先获取活动窗口的会话,然后在对应的窗口上执行所需的 *** 作。例如:

for(String windowHandle : drivergetWindowHandles()){

try { driverswitchTo()window(handle); } catch(NoSuchWindowException e){ Systemoutprintln(“Exception while switching browser window”); }

}

3 NoAlertPresentException

当WebDriver尝试着切换到某个不存在或无效的警报时,Selenium可能会产生此类异常。对此,我建议开发者使用显式、或适当的等待时间,来处理浏览器的各类警报。倘若仍然等不到警报的话,catch块可以捕获该异常。例如:

try {

driverswitchTo()alert()accept(); } catch(NoSuchAlertException e){

Systemoutprintln(“WebDriver couldn’t locate the Alert”); }

4 ElementNotVisibleException

该异常被定义为ElementNotInteractableException类的子类。当WebDriver尝试着对不可见的元素、或不可交互的元素执行各项 *** 作时,Selenium可能会产生此类异常。对此,我建议开发者在的确需要之处,让Selenium进行适当的超时等待。例如:

try { driverfindElement(Byid("form-save"))click(); } catch(ElementNotVisibleException e){

Systemoutprintln(“WebDriver couldn’t locate the element”); }

5 ElementNotSelectableException

该异常属于InvalidElementStateException类的子类。在Selenium中,ElementNotSelectableException表明某个元素虽然存在于网页上,但是无法被WebDriver所选择。

catch块不但可以处理Selenium中的此类异常,而且可以使用相同或不同的 技术 ,重新选择相同的元素。例如:

try {

Select dropdown = new Select(driverfindElement(Byid(“swift”))); } catch(ElementNotSelectableException e){

Systemoutprintln("Element could not be selected")}

6 NoSuchSessionException

Selenium通过driverquit()命令退出自动化的浏览器会话后,以及在调用某个测试方法时,会产生此类异常。当然,如果浏览器崩溃或出现断网,该异常也可能会发生。为了避免出现NoSuchSessionException,我们可以在测试套件结束时,退出浏览器,并确保用于 自动化测试 的浏览器版本的稳定性。例如:

private WebDriver driver;

@BeforeSuite

public void setUp(){ driver = new ChromeDriver(); }

@AfterSuite

public void tearDown(){ driverquit(); }

7 StaleElementReferenceException

当DOM中不再存在程序所需的元素时,Selenium将抛出StaleElementReferenceException。当然,如果DOM未能被正确加载、或WebDriver被卡在错误的页面上时,也可能会产生这种异常。对此,您可以使用catch块捕获该异常,并且使用动态的XPath、或尝试着重新刷新页面。例如:

try { driverfindElement(Byxpath(“//[contains(@id,firstname’)]”))sendKeys(“Aaron”);

} catch(StaleElementReferenceException e){

Systemoutprintln("Could not interact with a desired element")}

8 TimeoutException

当WebDriver超过了执行下一步的等待时限时,Selenium中可能会产生此类异常。Selenium的各种等待通常被用于避免出现ElementNotVisibleException之类的异常。不过,即使在使用了适当的等待之后,如果元素仍然不可交互,那么TimeoutException也会被抛出。为此,我们必须通过执行手动测试,来检验元素的延时性,以便采取进一步的处理等待。

9 InvalidSelectorException

当使用无效的或不正确的选择器时,Selenium中会抛出此类异常。当然,类似情况也可能发生在创建XPATH时。对此,我们需要在将代码推送到主分支之前,检查测试脚本,并测试脚本的端到端流程。此外,SelectorHub和ChroPath等工具,也可以被用于验证定位器。

10 NoSuchFrameException

NoSuchFrameException属于NotFoundException类的子类。当WebDriver尝试着切换到当前网页上无效的、或不存在的框架时,Selenium可能会产生此类异常。为此,我们需要首先确保框架的名称或id是正确的;其次,应确保框架的加载不会过于消耗时间。当然,如果在网页上加载框架的确非常耗时的话,则需要修正相应的等待处理。例如:

try {

driverswitchTo()frame("frame_1"); } catch(NoSuchFrameException e){

Systemoutprintln("Could not find the desired frame")

}

小结

综上所述,为了适应各种场景,异常处理对于任何自动化脚本和逻辑结构都是至关重要的。请您务必在了解每个异常特征的基础上,有选择性地在自动化脚本中使用上述十种有关Selenium的常用异常处理命令。

Web自动化测试中处理d出框的相关方法(python语言):

alert = driverswitch_toalert # 获取d出框对象

alerttext # 获取d出框的提示内容

alertaccept() # 点击确定按钮,关闭d出框

全套的课程可以找传智播客的,很多大牛的老师讲的都很全,主要是有配套资料哈。

首先js是没有getElementByXpath这个方法的,你可以看看是不是有frame标签没切进去。或者用documentquerySelector('inputnav-search-input')试试看看能不能获取到控件

可以啊,

如果是 IDE 有两种方法: storeAttribute 和storeValue

storeAttribute("css=#servType option:contains('上海')@value","vauleA");

storeValue("css=#servType option:contains('上海')","vauleB");

如果是RC, 就用getAttribute和getValue

getAttribute("css=#servType option:contains('上海')@value");

getValue("css=#servType option:contains('上海')");

<html >

<head>

<title>无标题文档</title>

<script language="javascript" type="text/javascript">

function judge()

{

if (documentform1nicknamevalue=="")

{alert("请输入你的昵称");return false;}

if (documentform1qqvaluelength<5||documentform1qqvaluelength>9)

{alert("请输入你正确的QQ号");return false;}

var mailstr;

mailstr=documentform1mailvalue;

if (mailstrindexOf("@")==-1)

{alert("请输入你正确的E-mail地址");return false;}

if (documentform1liuyanvalue=="")

{alert("请输入留言!");return false;}

return true;

}

</script>

</head>

<body>

<form name="form1" method="post" action="" onsubmit="return judge()">

昵称:

<input name="nickname" type="text" id="nickname" size="13" maxlength="20">

QQ号:

<input name="qq" type="text" id="qq" size="16" maxlength="10">

E-mail:

<input name="mail" type="text" id="mail" size="35">

个人网站:

<input name="wanzhan" type="text" id="wanzhan">

<input type="submit" name="Submit" value="提交">

<input name="reset" type="reset" id="reset" value="重置">

</form>

</body>

</html>分享给你的朋友吧:i贴吧 新浪微博腾讯微博QQ空间人人网豆瓣MSN

对我有帮助

0

# coding:utf-8

from seleniumimport webdriver

from seleniumwebdriversupportwaitimport WebDriverWait

from seleniumwebdriversupportimport expected_conditionsas EC

from seleniumwebdrivercommonbyimport By

from seleniumwebdrivercommonaction_chainsimport ActionChains

from seleniumwebdriversupportselectimport Select

# By的用法

# driverfind_element("id", "kw")

# driverfind_element(ByID, "kw")

class Base():

'''基于原生的selenium做二次封装'''

    def __init__(self, driver):

selfdriver = driver

selftimeout =10

        selft =05

    def findElement(self, locator, value=''):

'''定位元素,返回元素对象,10s钟没定位到,Timeout异常,locator传元组'''

        if not isinstance(locator, tuple):

print("locator的参数类型错误,必须穿元组类型,如:('id', 'kw')")

else:

print("正在定位元素,定位方式为→{0},定位元素为→{1}"format(locator[0], locator[1]))

if value !='':# value 值定位

                ele = WebDriverWait(selfdriver, selftimeout, selft)until(

ECtext_to_be_present_in_element_value(locator, value))

return ele

else:# 默认为此方法常规定位

                try:

ele = WebDriverWait(selfdriver, selftimeout, selft)until(

ECpresence_of_element_located(locator))

return ele

except:

print("定位失败,定位方式为→{0},定位元素为→{1}"format(locator[0], locator[1]))

return []

def findElements(self, locator, value=''):

'''定位元素,返回元素对象,10s钟没定位到,Timeout异常,locator传元组'''

        if not isinstance(locator, tuple):

print("locator的参数类型错误,必须穿元组类型,如:('id', 'kw')")

else:

print("正在定位元素,定位方式为→{0},定位元素为→{1}"format(locator[0], locator[1]))

if value !='':# value 值定位

                eles = WebDriverWait(selfdriver, selftimeout, selft)until(

ECtext_to_be_present_in_element_value(locator, value))

return eles

else:# 默认为此方法常规定位

                try:

eles = WebDriverWait(selfdriver, selftimeout, selft)until(

ECpresence_of_all_elements_located(locator))

return eles

except:

print("定位失败,定位方式为→{0},定位元素为→{1}"format(locator[0], locator[1]))

return []

def sendKeys(self, locator, text=''):

try:

selffindElement(locator)send_keys(text)

except:

print("text:%s输入错误" % text)

def click(self, locator):

try:

selffindElement(locator)click()

except:

print("点击失败")

def clear(self, locator):

try:

selffindElement(locator)clear()

except:

print("清空内容失败")

def isSelected(self, locator, Type=''):

''' 判断元素是否被选中,返回bool值 及点(选中/取消选中)'''

        ele =selffind(locator)

try:

if Type =='':# 如果type参数为空,返回元素是否为选中状态,True/False (默认)

                r = eleis_selected()

return r

elif Type =='click':# 如果type参数为click,执行元素的点击 *** 作

                eleclick()

else:

print("type参数 {0} 错误,仅可为click或"format(Type))

except:

return False

    def isElementExist(self, locator):

'''判断单个元素是否在DOM(元素树)里面'''

        try:

selffindElement(locator)

return True

        except:

return False

    def is_title(self, title=''):

'''判断当前页面title是否为title,返回bool值'''

        try:

result = WebDriverWait(selfdriver, selftimeout, selft)until(ECtitle_is(title))

return result

except:

return False

    def is_title_contains(self, title=''):

'''判断当前页面title名是否含有title,返回bool值'''

        try:

result = WebDriverWait(selfdriver, selftimeout, selft)until(ECtitle_contains(title))

return result

except:

return False

    def is_text_in_element(self, locator, text=''):

'''判断当前获取到的text含text,返回bool值'''

        try:

result = WebDriverWait(selfdriver, selftimeout, selft)until(

ECtext_to_be_present_in_element(locator, text))

return result

except:

return False

    def is_value_in_element(self, locator, _value=''):

'''返回bool值, value为空字符串,返回False'''

        if not isinstance(locator, tuple):

print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")')

try:

result = WebDriverWait(selfdriver, selftimeout, selft)until(

ECtext_to_be_present_in_element_value(locator, _value))

return result

except:

return False

    def get_title(self):

'''获取title'''

        return selfdrivertitle

def get_text(self, locator):

'''获取文本'''

        try:

result =selffindElement(locator)text

return result

except:

print("获取text失败")

return ""

    def get_attribute(self, locator, name):

'''获取属性'''

        try:

element =selffindElement(locator)

return elementget_attribute(name)

except:

print("获取%s属性失败" % name)

return ""

    def select_by_index(self, locator, index=0):

'''通过索引,index是索引第几个,从0开始,默认选第一个'''

        element =selffind(locator)# 定位select这一栏

        Select(element)select_by_index(index)

def select_by_value(self, locator, value):

'''通过value属性'''

        element =selffind(locator)

Select(element)select_by_value(value)

def select_by_text(self, locator, text):

'''通过文本值定位'''

        element =selffind(locator)

Select(element)select_by_visible_text(text)

# 这里只写了几种方法,后续有需要用到的定位方法或者 *** 作,可以继续封装起来然后调用

if __name__ =='__main__':

driver = webdriverChrome()

web = Base(driver)

driverget(">

以上就是关于你需要知道的有关Selenium异常处理的都在这儿全部的内容,包括:你需要知道的有关Selenium异常处理的都在这儿、使用Selenium框架在做Web自动化测试时,如何处理d出框、Selenium webdriver 给动态ID的日历控件赋值(python)等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/10083365.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-05
下一篇2023-05-05

发表评论

登录后才能评论

评论列表(0条)

    保存