[英]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.