Python 中的硒:选择一个选项

Selenium in Python: Selecting an Option

我在使用 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 enterprise 并使用selenium marionette 和Firefox developer edition 49.0a2

更新: 这似乎只有在 python 中使用 Marionette 时才会发生。我在使用和不使用 Marionette 的情况下在 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")

已编辑 :- 以上代码仅 select select 框中提供的选项。如果你想在选项 selected 时也触发 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.

希望它对你有用..:)