使用selenium API在页面超时后在python中执行函数

时间:2015-07-18 22:00:43

标签: javascript python selenium

我有一个python脚本,它使用了selenium和chrome webdriver。当我加载页面时,它会因为某些javascript尝试加载而卡住。如果我运行该行:

driver.execute_script("$(window.stop())")

偶尔(但不可靠)可以模拟停止浏览器操作。我的另一个想法是将page_load_timeout更改为5s。当这个讨厌的javascript没有加载时,这将引发错误。我想阻止页面加载超时,但然后运行我最初想要运行的功能...我该如何实现?

1 个答案:

答案 0 :(得分:1)

一种方法是,您必须通过检查断言哪个元素可以执行延迟,并且使用元素的#id,您可以等待该元素以超时加载。

try:
    WebDriverWait(driver, 60).until((EC.visibility_of_element_located(By.Id, 'id')))

except TimeoutException:
    pass

或者你可以使用 staleness_of 方法,在相关的SO答案中解释,

    @contextlib.contextmanager
    def wait_for_page_load(self, timeout=30):
        old_page = self.find_element_by_tag_name('html')
        yield
        WebDriverWait(self, timeout).until(staleness_of(old_page))