简体   繁体   English

列出Selenium Python中的选定选项

[英]List selected options in Selenium Python

I'm trying to list the selected options from the page. 我正在尝试列出页面中的选定选项。 But nothing is printed with below code. 但是下面的代码没有任何内容。 Any help will be appreciated. 任何帮助将不胜感激。

HTML code: HTML代码:

<select class="chosen-select" id="tag_opts" name="tag_opts[]" tabindex="-1" multiple="true" data-placeholder="Select a call tag here" disabled="disabled">
<optgroup label="TAGS">
    <option value="1" selected="selected">1</option>
    <option value="2" selected="selected">2</option>
    <option value="3" selected="selected">3</option>
    <option value="4" selected="selected">4</option>                      
</optgroup>
</select>

What I tried: 我试过的

  el = driver.find_element_by_id("tag_opts")
  for option in el.find_elements_by_tag_name('option'):
     if option.text in labels:
     print(option)

I tried with many other options but couldn't succeed. 我尝试了许多其他选择,但未能成功。

Just comment out the 'if' statement and print(option.text) 只需注释掉'if'语句并打印(option.text)

el = driver.find_element_by_id("tag_opts")
for option in el.find_elements_by_tag_name('option'):
   #if option.text in labels:
   print(option.text)

PS your if statement refers to a 'labels' object that isn't defined. PS您的if语句引用的是未定义的“标签”对象。 So it will never match anything 所以它永远不会匹配任何东西

Use Select to handle <select> elements : 使用Select处理<select>元素:

select = Select(driver.find_element_by_id("tag_opts"))
options = select.options
for option in options:
 print(option.text)     #or print(option.get_attribute("value"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM