How to replace innerHTML code using Selenium Webdriver C#?

Deadly 提交于 2021-02-05 12:13:05

问题


HTML CODE:

<select name="ddlFruit" id="ddlFruit" class="Searchddl">
    <option value="">Select</option>
    <option value="447">Grapes</option>
    <option value="448">Mango</option>
    <option selected="selected" value="449">Apple</option>
</select>

How can i replace

selected="selected"

to other options using selenium webdriver.

Eg:

<select name="ddlFruit" id="ddlFruit" class="Searchddl">
    <option value="">Select</option>
    <option selected="selected" value="447">Grapes</option>
    <option value="448">Mango</option>
    <option value="449">Apple</option>
</select>

回答1:


You can execute js script to modify attribute:

var webDriver = new ChromeDriver();
var jsExecutor = (IJavaScriptExecutor)webDriver;
var webElement = webDriver.FindElement(By.Id('id'));
jsExecutor.ExecuteScript("arguments[0].setAttribute('selected','selected');",webElement);



回答2:


Select dropdown = new Select(driver.findElement(By.id("identifier")))
dropdown.selectByVisibleText("option")

where identifier is a way of finding the drop down, and option is the option to select.




回答3:


Option selected Property

The selected option property sets or returns the selected state of an option.

As per the HTML:

<select name="ddlFruit" id="ddlFruit" class="Searchddl">
    <option value="">Select</option>
    <option value="447">Grapes</option>
    <option value="448">Mango</option>
    <option selected="selected" value="449">Apple</option>
</select>

The option with text as Apple is selected.


This usecase

The selected property can be replaced to other options only by selecting the other <option>.

To select the <option> with text as Grapes you need to induce WebDriverWait for the ElementToBeClickable() and you can use either of the Locator Strategies:

  • Using CssSelector and SelectByValue():

    new SelectElement(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("select.Searchddl#ddlFruit")))).SelectByValue("447");
    
  • Using XPath and SelectByText():

    new SelectElement(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("//select[@class='Searchddl' and @id='ddlFruit']")))).SelectByText("Grapes");
    


来源:https://stackoverflow.com/questions/65999006/how-to-replace-innerhtml-code-using-selenium-webdriver-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!