【发布时间】:2019-10-25 21:43:01
【问题描述】:
长话短说 - 我有一个没有 ID 并且有一个复合类的按钮(所以 selenium 讨厌它/找不到它)。所以我使用 XPath 选择器,效果很好
driver.findElement(By.xpath("//input[@value='Continue to Payment']")).click()
但按钮会根据所使用的语言而变化。
所以现在,我有
if (driver.findElement(By.xpath("//input[@value='Continue to Payment']")).isDisplayed()){
driver.findElement(By.xpath("//input[@value='Continue to Payment']")).click();
}
else if (driver.findElement(By.xpath("//input[@value='Paiement']")).isDisplayed()){
driver.findElement(By.xpath("//input[@value='Paiement']")).click();
}
else if ( same thing as above but for another language)
但是当 Selenium 在通过第一个 if 语句后出错时:
no such element: Unable to locate element:{"method":"xpath","selector":"//a[contains(text(),'Checkout')]"}
我知道该元素不存在.. 所以我不希望它做任何事情并继续下一个 if else 语句。 我在这里想念什么?
【问题讨论】:
-
我认为你错过了 try/catch。您也可以使用 findElements 来获取列表。如果列表大小>0,您已经找到它.... 类似这样的内容:wait = new WebDriverWait(driver, ec_Timeout); List
element = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(your_xpath))); if (element.size() > 0) {....} (但你还是应该使用 try/catch...)等待会抛出超时... -
分享页面的HTML,也许还有其他方法可以定位输入。
-
@pcalkins 谢谢!!这非常适合转移到第二个值!可以说它既不是第一个也不是第二个。并且 catch 也会有一个例外。我会尝试 {code A - not there} catch{ other code - not there} Try {code c} or Try{ code A +Code B] Catch{Code C}
-
想到的一件事是提前初始化 List
。如果最后列表大小> 0,则单击第一个元素...(在找到或未找到所有元素之后...)我想您还可以创建一个函数,如果一个项目返回列表被发现。如果已经找到,这将避免检查更多语言。 -
请尝试/捕获每个单独的 findElements() 调用...此外,如果元素不是通过 javascript 创建的,则不需要 webdriverwait。