簡體   English   中英

如何單擊與硒和python不可交互的下拉菜單,然后選擇一個選項?

[英]How to click not interactable dropdown with selenium and python and select one option?

我有ID為“ drp_autogen0”的下拉列表。 我想單擊下拉列表,以查看下拉選項。 當我嘗試使用Python和Selenium單擊它時,出現以下錯誤:selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互我已附加了下拉菜單的打印屏幕。 我希望能夠從列表中選擇“上個月”,但由於沒有單擊下拉菜單,因此我沒有走那么遠。 https://snipboard.io/xDM1Un.jpg

單擊下拉菜單的代碼在這里:

html_list = driver.find_element_by_id("drp_autogen0")
html_list.click()

下拉按鈕的網絡代碼為:

<button type="button" class="comiseo-daterangepicker-triggerbutton ui-button ui-corner-all ui-widget comiseo-daterangepicker-bottom" id="drp_autogen0">22 Nov 2019<span class="ui-button-icon-space"> </span><span class="ui-button-icon ui-icon ui-icon-triangle-1-s"></span></button>

上個月的網絡代碼為:

<div id="ui-id-5" tabindex="-1" role="menuitem" class="ui-menu-item-wrapper">Last month</div>

如果沒有,請檢查DOM在運行時是否沒有更改,那么有兩種方法可以解決此異常:

1.隱式等待

driver.manage().timeouts().implicitly Wait(10, TimeUnit.SECONDS);

2. WebDriver等待:

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("<Element path>")));

如果您收到ElementNotInteractable錯誤消息,則可以嘗試使用Javascript單擊以下方法來解決此問題:

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

# first, wait for the button to exist
html_list = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "drp_autogen0")))

# now click with Javascript
driver.execute_script("arguments[0].click();", html_list)

# now, click last month -- wait for it to exist first!
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[text()='Last month']"))).click()

此代碼示例對所需元素調用WebDriverWait ,以確保在單擊它們之前將其完全加載到頁面上。

然后,我們使用Javascript單擊第一個button元素,以解決ElementNotInteractable異常。 下拉列表展開后,我們等待Last Month選項存在,然后再嘗試單擊它。

即使按鈕/下拉選項似乎立即出現在頁面上,Selenium / Python也會在DOM中快速移動,因此driver可能會嘗試單擊尚不存在的內容。 WebDriverWait語句僅在嘗試單擊之前確保該元素存在於頁面上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM