如何遍历下拉列表并单击每个选项?

时间:2018-04-18 05:29:13

标签: python selenium webdriver

id继续更改下拉列表,下面是代码:

    <select class="select150" 
    onchange="document.getElementById('id1e_hf_0').value='? 
    wicket:interface=:5:remitReaderSearchForm:orgSelection::
    IOnChangeListener::&amp;
    wicket:pcxt=RemitReaderSearchPage';document.getElementById
   ('id1e').submit();" name="orgSelection" id="id1f">
  <option value="">Select One</option>
  <option value="7623">MCH - Cardiovascular Surgery</option>
  <option value="7598">MCH - Dept. of Orthopedics</option>
  <option value="7610">MCH - Emergency Physicians</option>
  <option value="7603">MCH - ENT</option>
  <option value="13043178">MCH Telehealth</option>
  <option value="13043153">NCH Genetics</option>
  <option value="13043155">NCH Hospitalist</option>
  <option value="13007836">NCH Neurology</option>
  </select>

以下是代码:

        select = Select(driver.find_element_by_class_name("select150"))
        options = select.options
        for index in range(0, len(options) - 1):
            select.select_by_index(index)

回溯:

  select = Select(driver.find_element_by_class_name("select150"))
  File "C:\Users\dm050767\Python27\lib\site- 
  packages\selenium\webdriver\remote\webdriver.py", line 555, in 
  find_element_by_class_name
  return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Users\dm050767\Python27\lib\site- 
  packages\selenium\webdriver\remote\webdriver.py", line 955, in 
  find_element
  'value': value})['value']
  File "C:\Users\dm050767\Python27\lib\site- 
  packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
  self.error_handler.check_response(response)
  File "C:\Users\dm050767\Python27\lib\site- 
  packages\selenium\webdriver\remote\errorhandler.py", line 242, in 
  check_response
  raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.NoSuchElementException: Message: no such 
 element: Unable to locate element: {"method":"class 
 name","selector":"select150"}
(Session info: chrome=65.0.3325.181)
(Driver info: chromedriver=2.37.544315 

(730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform = Windows NT 10.0.15063    x86_64的)

1 个答案:

答案 0 :(得分:0)

要选择所有选项,您需要使用range(0, len(options))代替range(0, len(options) - 1)

请注意,range(start, end)将生成从start(包括)到end的索引(不包括)

您也可以尝试使用以下循环:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

select = Select(wait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "select150"))))
options = select.options

for option in options:
    select.select_by_visible_text(option.text)