Python中的Selenium:选择一个选项

时间:2016-07-06 19:39:24

标签: python selenium firefox selenium-webdriver firefox-marionette

我没有运气从<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与marionette和Firefox开发人员版49.0a2

更新:这只是在python中使用Marionette时发生的。我在使用和不使用Marionette的Java中尝试了相同的代码并且它可以工作

1 个答案:

答案 0 :(得分: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.

希望它对您有用.. :)