问题
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