WebDriverWait 未按预期工作

WebDriverWait not working as expected

我正在使用 selenium 抓取一些数据。

我正在点击的页面上有一个按钮 "custom_cols"。此按钮为我打开 window,我可以在其中 select 我的专栏。

这个新的 window 有时需要一些时间才能打开(大约 5 秒)。所以为了处理这个我使用了

WebDriverWait 

延迟为 20 秒。但有时它无法 select 在新的 window 上找到元素,即使该元素是可见的。在其余时间正常工作时,这种情况只会发生十次一次。

我在其他地方也使用了相同的功能 (WebDriverWait),它按预期工作。我的意思是它等到元素变得可见,然后在找到它的那一刻点击它。

我的问题是为什么新 window 上的元素不可见,即使我正在等待元素变得可见。要在这里添加,我试图增加延迟时间,但我仍然偶尔会收到该错误。

我的代码在这里

def wait_for_elem_xpath(self, delay = None, xpath = ""):
    if delay is None:
        delay = self.delay

    try:
        myElem = WebDriverWait(self.browser, delay).until(EC.presence_of_element_located((By.XPATH , xpath)))
    except TimeoutException:
        print ("xpath: Loading took too much time!")
    return myElem
select_all_performance = '//*[@id="mks"]/body/div[7]/div[2]/div/div/div/div/div[2]/div/div[2]/div[2]/div/div[1]/div[1]/section/header/div'
self.wait_for_elem_xpath(xpath = select_all_performance).click()

一旦您等待元素并继续前进,因为您尝试调用 click() 方法而不是使用 presence_of_element_located() 方法,您需要使用 element_to_be_clickable() 如下:

try:
    myElem = WebDriverWait(self.browser, delay).until(EC.element_to_be_clickable((By.XPATH , xpath)))

更新

根据您在评论中的反问,这里是三种方法的详细信息:

presence_of_element_located

presence_of_element_located(locator)定义如下:

class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)

Parameter : locator - used to find the element returns the WebElement once it is located

Description : An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible or interactable (i.e. clickable). 

visibility_of_element_located

visibility_of_element_located(locator)定义如下:

class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)

Parameter : locator -  used to find the element returns the WebElement once it is located and visible

Description : An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.

element_to_be_clickable

element_to_be_clickable(locator)定义如下:

class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)

Parameter : locator - used to find the element returns the WebElement once it is visible, enabled and interactable (i.e. clickable).

Description : An Expectation for checking an element is visible, enabled and interactable such that you can click it.