Python中的Selenium:选择一个选项



我没有运气从使用硒的<select>中选择一个选项。 我已经参考了 https://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver

html代码如下:

<select name="Dropdownlistrequests" onchange="javascript:setTimeout(&#39;__doPostBack(&#39;Dropdownlistrequests&#39;,&#39;&#39;)&#39;, 0)" id="Dropdownlistrequests" style="height:51px;width:174px;Z-INDEX: 104; LEFT: 280px; POSITION: absolute; TOP: 72px">
    <option selected="selected" value="1">Previous Days</option>
    <option value="2">Previous Month</option>
    <option value="3">Last 12 Hours</option>
    <option value="4">Demand Poll</option>
    <option value="6">Custom</option>
</select>

我试过了

requests = driver.find_element_by_id("Dropdownlistrequests")
requests.click()
for option in requests.find_elements_by_tag_name('option'):
    if option.text == "Custom":
        option.click()
        break

requests = Select(driver.find_element_by_id("Dropdownlistrequests"))
requests.select_by_value("6")

b.find_element_by_xpath("//select[@id='Dropdownlistrequests']/option[text()='Custom']").click()

浏览器没有选择适当的选项,而是不执行任何操作,而是继续下一段代码。 它能不能与由onchange触发的javascript有关?

提供更多上下文:我正在运行Windows 7企业版,并将Selenium与木偶和Firefox开发人员版49.0a2

一起使用

更新:这只有在使用蟒蛇中的木偶时才会发生。我在有和没有木偶的 Java 中尝试了相同的代码,它有效

如果您的情况不是工作,您应该尝试如下.execute_script():-

select = driver.find_element_by_id("Dropdownlistrequests")
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }",select, "Custom")

已编辑:- 上面的代码仅从选择框中选择提供的选项。如果您希望在选择选项时也触发onchange事件,请尝试以下操作:-

select = driver.find_element_by_id("Dropdownlistrequests")
driver.execute_script("showDropdown = function (element) {var event; event = document.createEvent('MouseEvents'); event.initMouseEvent('mousedown', true, true, window); element.dispatchEvent(event); }; showDropdown(arguments[0]);",select)
# now you dropdown will be open

driver.find_element_by_xpath("//select[@id='Dropdownlistrequests']/option[text()='Custom']").click()
#this will click the option which text is custom and onchange event will be triggered.

希望它对您有用..:)

相关内容

最新更新