WebDriverWait没有按预期工作

时间:2018-04-11 12:43:17

标签: python selenium web-scraping

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

我点击的页面上有一个按钮说“custom_cols”。这个按钮为我打开一个窗口,我可以在那里选择我的列。

这个新窗口有时需要一些时间才能打开(大约5秒钟)。所以要处理这个我用过

WebDriverWait 

延迟为20秒。但有时候,即使元素可见,它也无法在新窗口中选择查找元素。在正常工作的其余时间内,这种情况只发生十次。

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

我的问题是为什么即使我在等待元素可见,新窗口上的元素也不可见。在这里添加我试图增加延迟时间,但我偶尔会得到那个错误。

我的代码在这里

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()

1 个答案:

答案 0 :(得分:2)

在您尝试调用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.