【问题标题】:Dropdown menus in python / seleniumpython / selenium中的下拉菜单
【发布时间】:2016-09-19 16:38:25
【问题描述】:

尝试使用 python 和 selenium 自动填充表单。下拉菜单 html 是:

<select id="typeOfTeacher" class="chosen-select-no-single ng-untouched ng-dirty ng-valid-parse ng-valid ng-valid-required" required="" ng-class="{ 'has-error' : positionDetailForm.typeOfTeacher.$invalid && !positionDetailForm.typeOfTeacher.$pristine }" ng-change="vm.setRequired()" tabindex="-1" ng-model="vm.data.typeOfTeacher" name="typeOfTeacher" data-placeholder="Select" style="display: none;">
<option value="" disabled="" selected="">Select</option>
<option class="ng-binding ng-scope" value="1" ng-repeat="teacherType in vm.teacherTypes">No position at the moment</option>
<option class="ng-binding ng-scope" value="2" ng-repeat="teacherType in vm.teacherTypes">Supply</option>
<option class="ng-binding ng-scope" value="3" ng-repeat="teacherType in vm.teacherTypes">Permanent</option>
</select>

Python 代码是:

elem = Select(browser.find_element_by_id('typeOfTeacher'))
elem.select_by_value("1")

错误是“元素当前不可见并且可能无法与之交互”。

【问题讨论】:

  • 您是否尝试过使用WevDriverWait 等到元素可见后再进行交互??

标签: python selenium selenium-webdriver


【解决方案1】:

我没有用过python的Select方法,但是我猜这个错误信息意味着菜单没有被打开,因此菜单中的一个元素仍然是隐藏的,不能与之交互。

试试这样的:

element = driver.find_element_by_id('typeOfTeacher').click()
driver.find_element_by_css_selector("[value=\"1\"]").click()

【讨论】:

    【解决方案2】:

    这样就可以了

    element = driver.find_element_by_id('typeOfTeacher').click()
    element.find_element_by_xpath(".//option[@value='1']").click()
    

    【讨论】:

      【解决方案3】:

      看起来像是时间问题。您应该尝试使用Waits

      我建议你,使用WebDriverWait 等到下拉菜单可见,然后再进行交互,如下所示:-

      from selenium import webdriver
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      
      element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "typeOfTeacher")))
      
      select = Select(element)
      select.select_by_value("1")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 2020-02-22
        • 2023-03-25
        • 2022-11-11
        相关资源
        最近更新 更多