Java 如何检查selenium选择器是否成功?
我目前正在用Appium为一个网站开发自动化UI测试。 我在testobject上用许多设备运行测试,我试图解决一些问题 我的示例代码如下:Java 如何检查selenium选择器是否成功?,java,selenium,appium,ui-automation,mobile-devices,Java,Selenium,Appium,Ui Automation,Mobile Devices,我目前正在用Appium为一个网站开发自动化UI测试。 我在testobject上用许多设备运行测试,我试图解决一些问题 我的示例代码如下: WebElement lexiconCollapsible = mDriver.findElement(By.xpath("//*[@id='1014']/a")); assertNotNull(lexiconCollapsible); ScrollHelper.scrollToElement(mDriver,lexiconCollapsible); Th
WebElement lexiconCollapsible = mDriver.findElement(By.xpath("//*[@id='1014']/a"));
assertNotNull(lexiconCollapsible);
ScrollHelper.scrollToElement(mDriver,lexiconCollapsible);
Thread.sleep(1000);
lexiconCollapsible.click();
这适用于许多设备,但不是所有设备。
在某些情况下,我得到以下错误代码:
org.openqa.selenium.InvalidSelectorException: Argument was an invalid selector (e.g. XPath/CSS). (WARNING: The server did not provide any stacktrace information)
异常在我想要单击元素的位置抛出,因此对象不是null
所以我的问题是:
是否有人找到了检查设备是否能够找到物体的解决方案?有没有类似的方法
我也尝试了css选择器、id等,但结果是一样的。来自Selenium文档
exception selenium.common.exceptions.InvalidSelectorException(msg=None, screen=None, stacktrace=None)[source]
Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression and it is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).
所以看起来您的选择器不正确,因为它只发生在XPATH中,所以您应该尝试css选择器
试试看
关于您的isObjectFound
方法,它看起来像是在您执行findElement
时找到的WebElement,您仅在click()
上获得异常。我建议您切换到CSS选择器以避免此异常。回答由JeffC提供。
函数之间的超时和等待时间有问题
Utility.implicitlyWaitForElementPresent(mDriver,By.xpath("//*[@id='1014']/a"));
WebElement lexiconCollapsible = mDriver.findElement(By.xpath("//* [@id='1014']/a"));
assertNotNull(lexiconCollapsible);
ScrollHelper.scrollToElement(mDriver,lexiconCollapsible);
Thread.sleep(1000);
lexiconCollapsible.click();
xpath的效果要好得多。不幸的是,正如我在最初的评论中所说的,我尝试切换到cssSelector,但没有多大帮助。我试过你的表情和我的:“#1014>a”,结果更糟。使用xpath,我得到了更积极的结果。@minhundje使用CSS选择器,你得到了什么异常?我得到:
org.openqa.selenium.InvalidSelectorException:参数是无效的选择器(例如xpath/CSS)。(警告:服务器未提供任何stacktrace信息)
并且在查找元素时测试失败。@minhundje在您的问题中提到,单击元素时测试失败。如果您的测试在查找元素时失败,则表示该元素不存在。或者您必须等待元素出现。发布你的HTML代码。你试过等待吗?等待XPath元素可见,然后继续。如果你没有也不知道如何。。。让我知道,我可以添加一些示例代码。我添加了一个自定义等待方法并再次测试:首先使用cssSelector,我得到了与以前相同的错误。第二个是xpath,结果是:它现在对所有四个设备都有效!非常感谢你的回答。我的新wait命令:Utility.implicitlyWaitForElementPresent(mDriver,By.xpath(“/*[@id='1014']/a”)代码>这是正确答案。谢谢你的帮助!没问题。请将您的工作代码作为答案发布并接受,以便将问题标记为已回答。谢谢我将在星期一做这件事。
Utility.implicitlyWaitForElementPresent(mDriver,By.xpath("//*[@id='1014']/a"));
WebElement lexiconCollapsible = mDriver.findElement(By.xpath("//* [@id='1014']/a"));
assertNotNull(lexiconCollapsible);
ScrollHelper.scrollToElement(mDriver,lexiconCollapsible);
Thread.sleep(1000);
lexiconCollapsible.click();