簡體   English   中英

硒-單擊由javascript生成的單選按鈕

[英]selenium - clicking on radio button generated by javascript

我的代碼是用Java編寫的。

我有一組由javascript動態生成的單選按鈕。 我要單擊其中之一。

我使用xpath,但是不起作用。 它說

線程“主要” org.openqa.selenium.NoSuchElementException中的異常:無法找到元素:

在谷歌瀏覽器上“檢查元素”后,我嘗試了下面的兩個deliveryType方法。

 //WebElement deliveryType = driver.findElement(By.xpath("//div[contains(@id, 'checkout-shipping-method-load')]//*[contains(@name, 'shipping_method')]"));
    //WebElement deliveryType = driver.findElement(By.cssSelector("[name='shipping_method'][id='s_method_matrixrate_matrixrate_5983']"));
    //deliveryType.click();

以下是該單選按鈕的檢查元素。

 <div id="checkout-shipping-method-load">
  <dl class="sp-methods">
  <dt>Select Shipping Method</dt>
    <dd>
        <ul>
          <li>
            <input name="shipping_method" type="radio" value="matrixrate_matrixrate_5983" id="s_method_matrixrate_matrixrate_5983" class="radio validation-passed">
<label for="s_method_matrixrate_matrixrate_5983">Standard Shipping<span class="price">NT$300</span></label></li>
         <li>
           <input name="shipping_method" type="radio" value="matrixrate_matrixrate_5991" id="s_method_matrixrate_matrixrate_5991" class="radio validation-passed">
<label for="s_method_matrixrate_matrixrate_5991">Express Shipping<span class="price">NT$1,200</span></label></li>
        </ul>
    </dd>
  </dl>
</div>

我試圖編碼我的腳本以單擊它。 我試圖讓我的xpath遵循“檢查元素”和“查看頁面源代碼”。 兩者都給我相同的錯誤,因為找不到這樣的元素。

如何使我的Selenium腳本單擊由javascript動態生成的單選按鈕之一?

我的xpath應該指向原始javascript編碼還是窗口加載后由javascript生成的html?

請幫助我。

已關閉:我使用了隱式等待來等待我的JavaScript運行並加載我的html。 加載后,我使用列表存儲了所有單選按鈕。 從列表中,按索引獲取。

感謝Girish Sortur和JeffC。

下面是我的代碼。

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> methods = driver.findElements(By.cssSelector("input[name='shipping_method']"));
methods.get(0).click();

單擊動態元素的最佳方法是等待它出現。 在Selenium中,您可以使用WebDriverWait()方法等待元素出現,直到它出現。 Selenium中使用ExpectedConditions來檢查期望值。 在這里您可以使用期望元素的可見性。 這是一個示例代碼-

WebElement radioBtn = driver.findElement(By.xpath("//input[@id='s_method_matrixrate_matrixrate_5983']"));
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOf(radioBtn));

您也可以嘗試使用FluentWait ,這是等待元素出現的最佳選擇。 這樣做的方法-

new FluentWait<WebElement>(radioBtn).
    withTimeout(50, TimeUnit.SECONDS).
    pollingEvery(2,TimeUnit.SECONDS);

FluentWait等待元素與我們指定的選項一起顯示。 輪詢以該時間間隔檢查元素的存在。 根據出現在DOM中的時間元素提供超時。 希望這可以幫助。

我會將與運送方法相對應的所有INPUT都拉到一個收集methods ,然后單擊我想要的一個。 示例代碼如下。

List<WebElement> methods = driver.findElements(By.cssSelector("input[name='shipping_method']"));
methods.get(0).click(); // clicks the first element, Standard Shipping

暫無
暫無

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

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