如何通过 Chrome 中的 webdriver 单击通过 Ajax 加载的元素

How to click an element which is loaded through Ajax through webdriver within Chrome

浏览器:ChromeV65

ChromeDriver: chromedriver.exe 2.37

网络驱动程序尝试单击元素时发生错误。下面是我的click():

def click(self):
    try:
        self.wait_for().visible()
        self._selenium_context().click()
    except Exception as e:
        raise NoSuchElementException

def visible(self):
    '''
    Check if the element is visible.
    :return:  True or exception.
    '''
    return Utils.wait_for(self.web_element.visible, self.interval, self.timeout)

我已经等待元素可见然后点击。但是抛出异常说 'Other element would receive the click' 如下:

selenium.common.exceptions.WebDriverException: Message: unknown error: Element <div class="learn-wrap" ng-click="changeTab(2)" ng-class="internal.tab == 2?'learn-selected':''">...</div> is not clickable at point (1026, 89). Other element would receive the click: <div class="loading-data ng-scope ng-animate ng-leave ng-leave-active" ng-if="internal.isAjaxing" data-ng-animate="2" style="">...</div>

即使我添加等待语句也会出错ajax加载完成点击元素:

driver.find_element(By.XPATH, "//div[contains(@class, 'learn') and (contains(@ng-if, '!internal.isAjaxing'))]")
driver.find_element(By.XPATH , element_xpath).click()

这种情况在 Chrome 上经常发生,可能 5 次失败中有 4 次。没用!

现在,我必须改用睡眠等待元素变为可点击。

有人可以帮忙吗?谢谢。

正如您提到的 Ajax 调用 并且您正在使用休眠等待元素可点击,相反,您需要使用 WebDriverWait 来使元素可点击,如下所示:

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

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'learn') and (contains(@ng-if, '!internal.isAjaxing'))]"))).click()

您可以使用操作 class 来点击元素,

语法:

Actions action = new Actions(driver);
action.moveToElement("Your Element").click().perform();