簡體   English   中英

使用 Selenium - JAVA 選擇單選按鈕時遇到問題

[英]Trouble selecting Radio buttons using Selenium - JAVA

我正在嘗試在 Chrome 上使用 Selenium 自動化一些測試。 在進入下一步之前,我遇到了選擇單選按鈕的問題。 我嘗試選擇單選按鈕的每種方法都經常出現“NoSuchElementException”錯誤。 下面是用於單選按鈕的 html 代碼,我正在嘗試 select 第一個“新(空)”。

<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, assemblyFile, virtualDocument], existingAssembly)">
    Existing Template, Assembly or View
    <br>
    <input type="radio" name="selections" value="assemblyFile" id="Assembly File" onclick="onSelection([emptyAssembly, existingAssembly, assemblyFile, virtualDocument], assemblyFile)">
    Assembly File
    <br>
    <input type="radio" name="selections" value="virtualDocument" id="Virtual Document" onclick="onSelection([emptyAssembly, existingAssembly, assemblyFile, virtualDocument], 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 錯誤。

我嘗試按照下面其他線程的建議通過創建一個列表來選擇它,為此我收到一個 idex 錯誤,因為該列表不包含任何內容:

webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> methods = webDriver.findElements(By.name("selections"));
methods.get(0).click();

要在元素上click() ,文本為New(空) ,您可以使用以下任一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 ,並且您可以使用以下任一定位器策略

  • 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 代碼創建一個 local.html 文件,然后在該本地 HTML 文件上再次嘗試您的方法。 我已經嘗試過,您的所有方法都運行良好。

問題不在於您的方法或腳本,而在於其他問題。 可能是這些元素是動態的或當時不可點擊。

那么您能否提供更多詳細信息。 就像場景或測試用例是什么一樣,達到該點的先前步驟是什么(單擊那些單選按鈕)。 如果可能的話,請提供更多 HTML 代碼(父標簽)和您網頁的屏幕截圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM