【问题标题】:Cannot save value in span control using Selenium Webdriver and Java无法使用 Selenium Webdriver 和 Java 在跨度控制中保存值
【发布时间】:2017-03-07 16:15:51
【问题描述】:

我正在使用 Selenium Webdriver + Java 进行自动化测试,但遇到了在 span 控件中设置值的问题。 我有一个包含客户端列表的下拉列表,默认选择第一个客户端 - 'Harry',但我需要将客户端更改为默认值以外,例如到“西蒙”。

我尝试在这里搜索并附带以下代码:

Webelement element = driver.findElement(By.xpath("//*[@id=\"SelectedClientDirectorID_chosen\"]/a/span"));                                                
((JavascriptExecutor)driver).executeScript("arguments[0].innerText = 'Simon'", element);

似乎没问题,找到了元素,在执行脚本时将其 innerText 属性更改为“Simon”。 但只要我点击页面上的“保存”按钮,记录就会保存为第一个值 - 'Harry'。

我找不到关于为什么不保存新值的答案。

HTML 看起来像:

<div class="chosen-container chosen-container-single" style="width: 100%;" title="" id="SelectedClientDirectorID_chosen">
	<a class="chosen-single" tabindex="-1">
	<span class="">Harry</span>
	<div><b></b></div>
</a>
<div class="chosen-drop">
		<div class="chosen-search">
			<input type="text" autocomplete="off">
		</div>
		<ul class="chosen-results">
			<li class="active-result result-selected" style="" data-option-array-index="0">Harry</li>
			<li class="active-result result-selected" style="" data-option-array-index="1">Simon</li>
			<li class="active-result result-selected" style="" data-option-array-index="2">Robin</li>
			<li class="active-result" style="" data-option-array-index="3">Brian</li>
			<li class="active-result" style="" data-option-array-index="4">Rupert</li>
			<li class="active-result" style="" data-option-array-index="5">Greg</li>
		</ul>
	</div>
</div>

欣赏任何线索。

【问题讨论】:

    标签: java html selenium webdriver


    【解决方案1】:

    更改 innerText 值可能不会为您带来预期的结果。您可以尝试像真实用户一样点击下拉菜单并选择所需选项:

    driver.findElement(By.xpath("xpathForDropDownButton")).click();
    driver.findElement(By.xpath("//li[text()='Simon']")).click();
    

    您可能还需要等待一段时间,直到所需元素变为可点击:

    WebDriverWait wait = new WebDriverWait(driver, 15);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpathForDropDownButton"))).click();
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[text()='Simon']"))).click(); 
    

    【讨论】:

      【解决方案2】:

      同样使用下面的代码。您需要从下拉列表中选择值,而不是设置 innerText。

      WebElement element = driver.findElement(By.xpath("//ul[@class='chosen-results']/li[normalize-space()='Simon']"));
      ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
      

      【讨论】:

        猜你喜欢
        • 2019-05-11
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 2015-04-23
        • 2020-04-13
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多