python/selenium中的下拉菜单

2024-03-28 15:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试使用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代码是:

^{2}$

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


Tags: invaluerequiredvmngselectclassbinding
3条回答

我没有使用pythonselect方法,但是我猜错误消息意味着菜单没有被打开,因此菜单中的一个元素仍然是隐藏的,无法与之交互。在

试试这样的方法:

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

看来是时间问题。您应该尝试使用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")

这会有用的

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

相关问题 更多 >