如何解决使用Selenium-JAVA
我正在尝试在Chrome上使用Selenium自动化一些测试。在进入下一步之前,我在选择单选按钮方面遇到了问题。我尝试选择单选按钮的每种方法都不断收到“ NoSuchElementException”错误。下面是用于单选按钮的html代码,我试图选择第一个“新建(空)”。
<td>
<input type="radio" name="selections" value="emptyAssembly" id="New (Empty)" onclick="onSelection([emptyAssembly,existingAssembly,assemblyFile,virtualDocument],emptyAssembly)">
New (Empty)
<br>
<input type="radio" name="selections" value="existingAssembly" id="Existing Template,Assembly or View" onclick="onSelection([emptyAssembly,existingAssembly)">
Existing Template,Assembly or View
<br>
<input type="radio" name="selections" value="assemblyFile" id="Assembly File" onclick="onSelection([emptyAssembly,assemblyFile)">
Assembly File
<br>
<input type="radio" name="selections" value="virtualDocument" id="Virtual Document" onclick="onSelection([emptyAssembly,virtualDocument)">
Virtual Document
<br>
</td>
下面是我尝试选择它的几种方法(线程睡眠在那里,因为这是人们用单选按钮观察到的常见问题):
Thread.sleep(5000);
webDriver.findElement(By.xpath("//input[@id='New (Empty)']")).click();
Thread.sleep(5000);
webDriver.findElement(By.id("New (Empty)")).click();
我尝试了其他方法,但没有跟踪它们,它们都引发了相同的NoSuchElementException错误。
我尝试按照下面其他线程上的建议通过创建一个列表来选择它,因为列表不包含任何内容,因此我遇到了同义错误:
webDriver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
List<WebElement> methods = webDriver.findElements(By.name("selections"));
methods.get(0).click();
解决方法
要对文本为新建(空)的元素进行click()
,则可以使用以下Locator Strategies中的任意一个:
-
cssSelector
:webDriver.findElement(By.cssSelector("input[id*='Empty'][value='emptyAssembly']")).click();
-
xpath
:webDriver.findElement(By.xpath("//input[@value='emptyAssembly' and contains(@id,'Empty')]")).click();
但是,由于该元素是动态元素,因此在元素上click()
时,您需要为elementToBeClickable()
引入WebDriverWait,并且可以使用以下任一 Locator策略:
-
cssSelector
:new WebDriverWait(webDriver,20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[id*='Empty'][value='emptyAssembly']"))).click();
-
xpath
:new WebDriverWait(webDriver,20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@value='emptyAssembly' and contains(@id,'Empty')]"))).click();
尝试使用提供的HTML代码创建本地.html文件,然后在该本地HTML文件上再次尝试方法。我已经尝试过,并且您所有的方法都运行良好。
问题不在您的方法或脚本中,而是其他原因。那时这些元素可能是动态的或不可点击的。
因此,您可以提供更多详细信息。就像场景或测试用例一样,达到该点的先前步骤是什么(单击那些单选按钮)。然后,如果可能的话,再提供一些HTML代码(父标记)和您的网页的屏幕截图。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。