元素不可单击,因为另一个元素在python中隐藏了它

2024-04-23 08:27:28 发布

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

我正在尝试自动化访问点web配置。在这个过程中,我得到一个弹出窗口(类似于一个带有“Yes”和“No”的覆盖),我想点击它

我试图单击的覆盖的HTML代码:

<div id="generic-warning-dialog" class="dialog exclamation text-orphan" style="">
<div class="warning-content dialog-content text-orphan">Security Mode is disabled on one or more of your wireless networks. Your network could be open to unauthorized users. Are you sure you wish&nbsp;to&nbsp;proceed?</div>
    <div class="dialog-buttons text-orphan">
        <button class="cancel">No</button>
        <button class="submit" style="display: block;">Yes</button>
    </div>
</div> 

我试过了

browser.find_element_by_class_name("submit").click()

但我得到了以下错误:

raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementClickInterceptedException: Message: Element is not clickable at point (788,636.5) because another element obscures it

你能告诉我该怎么做吗? 我正在使用firefox和python


Tags: tonotextdivyouisstylebutton
3条回答

您可以用action类替换click事件

使用动作类:

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
actions.move_to_element("Your Web Element").click().perform()

根据您的问题和您共享的HTML,您需要诱导WebDriverWait以使所需的元素可以单击,您可以使用以下解决方案:

#to click on Yes button
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='warning-content dialog-content text-orphan' and contains(.,'Security Mode is disabled')]//following::div[1]//button[@class='submit']"))).click()
# to click on No button
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='warning-content dialog-content text-orphan' and contains(.,'Security Mode is disabled')]//following::div[1]//button[@class='cancel']"))).click()

注意:必须添加以下导入:

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

您正试图单击一个弹出窗口,当selenium尝试单击元素时,它可能在DOM中可用,但不可见,然后您将得到此错误。

解决方案是在单击之前等待该元素可单击/可见。下面是C#代码(您可以用Python编写等效代码):

WaitForElementToBeClickable(By.ClassName("submit"), 20);
browser.FindElement(By.ClassName("submit")).click();


public static void WaitForElementToBeClickable(By by, int timeout)
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout)).Until(ExpectedConditions.ElementToBeClickable(by));
    }

相关问题 更多 >