我的任务是在一个我没有编写源代码的网页上提供 Selenium 测试(使用Python)(我对Web开发不太了解,但据我所知,它是使用D3 和 JQuery)。该网站生成图表,并且有一些带有选项的下拉菜单。我正在尝试使用这些选项创建所有可能的图表。为此,我从下拉菜单 WebElement 创建一个 Select 对象,并提取下拉菜单中每个选项的文本。随后,我使用此文本递归地浏览每个下拉列表并输入每个有效选项来生成图表。但是,我有时(并非总是如此,而且似乎相对随机)在尝试提取此选项列表时遇到 StaleElementReferenceException,这是因为以下代码(它发生在 options.append(op. get_attribute("text"))
行)。我一直在搜索有关此异常的先前问题和文档,但尚未找到对我有帮助的答案。
#find all of the options
# create list of string options before, so as to avoid StaleElementReferenceException's
# as much as possible
el = driver.find_element(By.ID,node.element)
d = Select(el)
options = []
for op in d.options:
try:
options.append(op.get_attribute("text"))
except StaleElementReferenceException:
print >>sys.stderr, 'StaleElementReferenceException getting text from \'' + node.element + '\' element'
任何输入都非常有帮助!谢谢。
编辑:以下是其中一个下拉列表的 HTML 片段示例:
<select class="dropdown" id="datatype" name="datatype" style="display: none;">
<option value="solar_radiation" selected="selected">solar radiation</option>
<option value="windspeed">windspeed</option>
<option value="airtemperature">airtemperature</option>
...
</select>
最佳答案
我很怀疑d = Select(el)
如果您只想获取所有文本,也许您可以这样做:
optionNodes = driver.find_element_by_id("datatype").find_elements_by_tag_name("option")
options = []
for op in optionNodes:
options.append(op.get_attribute("text"))
如果上面的代码不起作用(虽然很奇怪),也许你可以尝试执行脚本,例如:
driver.execute_script("return Array.apply(null, document.getElementById('datatype').options).map(function (option) {return option.text})");
关于jquery - 迭代 Select 选项时出现 Python Selenium StaleElementReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107097/