无法使用 Python Selenium 单击下拉菜单

Unable to Click on Dropdown using Python Selenium

我正在尝试 select 下拉列表中的元素,但出现错误。

这里是 HTML:

<select id="childContextDDL" data-filter="contains" data-role="dropdownlist" data-template="dcf-context-picker" data-value-field="Value" data-text-field="DisplayText" data-bind="events: { change: childContextListChange }, source: childContextList.ChildContextList" style="display: none;">
<option value="1">NATION</option>
<option value="12">ATLANTIC</option>
<option value="16">CHARLOTTE, NC</option>

这是我正在尝试的代码 运行:

mySelect = Select(driver.find_element_by_id("childContextDDL"))
print('MySelect is: ',mySelect)
mySelect.select_by_visible_text('ATLANTIC')

我收到这个错误:

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable: Element is not currently visible and may not be manipulated

出现此错误的可能原因是什么?我对 Selenium 很陌生。

我还想在 select 之后单击该元素。

如果它说它当前不可见,您应该尝试使用以下选项之一暂停代码:

time.sleep(1) #This states to your code to stop for 1 second and the continue with the work.
WebDriverWait(driver, 10).until(EC.element_to_be_visible(BY.value, "12")) # tells the driver to wait a maximum of ten seconds until the value "12" is visible for the driver.

我猜 mySelect 元素(下拉菜单)不可见。
所以请尝试以下操作:

from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)

mySelect = Select(driver.find_element_by_id("childContextDDL"))

actions.move_to_element(mySelect).perform()
mySelect.select_by_visible_text('ATLANTIC')

如果以上方法不起作用(我看不到您正在处理的实际站点),则以下方法可以起作用,必须点击元素才能启用

action = TouchActions(driver)
action.tap(mySelect).perform()
mySelect.select_by_visible_text('ATLANTIC')

问题是 html 中的样式设置为 none。所以我不得不先把那个样式改成block让它可见,然后再进行点击操作。

这是有效的代码:

driver.execute_script("document.getElementById('childContextDDL').style.display = 'block';")

mySelect = Select(driver.find_element_by_id("childContextDDL"))
print('MySelect is: ',mySelect)
mySelect.select_by_visible_text('ATLANTIC')

randomClick = driver.find_element_by_id('dcf-user-info')
randomClick.click()