【发布时间】:2017-05-01 09:34:15
【问题描述】:
我正在使用 Python 和 Selenium 浏览网站。
在一个页面上,我试图通过一系列 5 个下拉框来工作。每个下拉框中的选项都是根据从上一个下拉列表中选择的内容动态生成的。
我被困在第三个下拉列表中,用户必须在其中选择一个状态。 加载后,检查的 HTML 如下所示:
<select name="state" class="pulldown" id="state" onchange="[javablob]">
<option value="">Select a State</option>
<option value='AK_N'> AK</option>
<option value='AL_N'> AL</option>
<option value='AR_Y'> AR</option>
...等等。
到目前为止我的代码是:
waitforstate = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.ID,"state")))
driver.implicitly_wait(10) #added because the ID is found but the states aren't loaded yet
state = Select(driver.find_element_by_id('state'))
但是选择我想要的状态不起作用:
state.select_by_visible_text("TN")
给...
Message: Given xpath expression ".//option[normalize-space(.) = "TN"]" is invalid:
WrongDocumentError: Node cannot be used in a document other than the
one in which it was created
这样做:
state.select_by_value("TN_Y")
给...
Message: Given css selector expression "option[value ="TN_Y"]" is invalid:
TypeError: can't access dead object
没有可供选择状态的索引。
当我尝试显示加载了哪些选项时:
all_options = state.options
for option in all_options:
print("Value is: %s" % option.get_attribute("value"))
...没有打印,甚至没有打印默认选项。但看来我可以选择和取消选择默认选项,使用这个:
state.select_by_visible_text("Select a State")
print "Select a state selected"
state._unsetSelected
print "Now it's unselected"
...运行没有错误。
我使用 Firefox 的 Selenium IDE 来导航页面,查看它是如何处理的,并且可以使用 id=state, label=TN. 选择它
我错过了什么?
【问题讨论】: