使硒驱动程序等到元素样式属性更改

Pyt*_*sta 2 python selenium python-3.x

如标题所示,需要等待动态加载的材料。每次滚动到页面末尾时,都会显示该材料。

当前正在尝试通过以下方法做到这一点:

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
WebDriverWait(driver, 5).until(expected_conditions.presence_of_element_located(
    (By.XPATH, "//*[@id='inf-loader']/span[1][contains(@style, 'display: inline-block')]")))
Run Code Online (Sandbox Code Playgroud)

xpath是这里的问题吗?即使使用硒滚动时显示样式确实发生了变化,它也会保持超时。

ale*_*cxe 5

我将等待display样式更改为inline-block具有自定义的“预期条件”并使用value_of_css_property()

from selenium.webdriver.support import expected_conditions as EC

class wait_for_display(object):
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            element = EC._find_element(driver, self.locator)
            return element.value_of_css_property("display") == "inline-block"
        except StaleElementReferenceException:
            return False
Run Code Online (Sandbox Code Playgroud)

用法:

wait = WebDriverWait(driver, 5)
wait.until(wait_for_display((By.XPATH, "//*[@id='inf-loader']/span[1]")))
Run Code Online (Sandbox Code Playgroud)

您还可以尝试调整轮询频率,以使其更频繁地检查状况:

wait = WebDriverWait(driver, 5, poll_frequency=0.1)  # default frequency is 0.5
Run Code Online (Sandbox Code Playgroud)