列出Selenium Python中的选定选项

时间:2018-08-12 09:22:43

标签: python python-3.x selenium web-scraping

我正在尝试列出页面中的选定选项。但是下面的代码没有任何内容。任何帮助将不胜感激。

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>

我尝试过的事情:

  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)

我尝试了许多其他选择,但没有成功。

2 个答案:

答案 0 :(得分:0)

只需注释掉'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)

您的if语句引用的是未定义的“标签”对象。所以永远不会匹配任何东西

答案 1 :(得分:0)

使用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"))