1

我没有运气从<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

更新:这似乎只在 python 中使用 Marionette 时发生。我在有和没有 Marionette 的情况下在 Java 中尝试了相同的代码,它都有效

4

1 回答 1

0

如果在你的情况下没有工作,你应该尝试.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.

希望它会为你工作.. :)

于 2016-07-07T06:46:23.060 回答