How to click an element which is loaded through Aj

2019-01-27 08:37发布

Browser : Chrome V65

ChromeDriver: chromedriver.exe 2.37

Error occurs while webdriver trying to click an element. The below is my 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)

I had already waited for element visible and then clicked. But exception was thrown saying 'Other element would receive the click' as below:

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>

Error occurs even if I add statement to wait ajax loading finished to click the element:

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

This happens on Chrome frequently, maybe 4 in 5 times failure. It doesn't work!

Now, I have to use sleep to wait element to be clickable instead.

Can anybody help? Thanks.

2条回答
ら.Afraid
2楼-- · 2019-01-27 09:17

You can use action class to click element,

Syntax:

Actions action = new Actions(driver);
action.moveToElement("Your Element").click().perform();
查看更多
太酷不给撩
3楼-- · 2019-01-27 09:19

As you mentioned Ajax Calls are involved and you are using sleep to wait for the element to be clickable, instead of that you need to use WebDriverWait for the element to be clickable as follows :

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()
查看更多
登录 后发表回答