【发布时间】:2017-04-29 17:56:07
【问题描述】:
我有一个关于隐式等待在 selenium 中的工作方式的问题。据我了解,隐式等待等到元素被定位/可见/存在,并具有给定的最大值。例如:
wait = WebDriverWait(driver,
10).until(EC.presence_of_element_located((By.CLASSNAME,'classname')))
这个语句让 selenium 等待,直到找到具有类名 'classname' 的元素,或者直到满足最长十秒的等待时间,对吧?
现在,我编写了一个从网站获取数据并使用隐式等待的脚本,如下所示:
def move_to_next_page():
(this function loads the next page)
def get_page_data():
wait = WebDriverWait(driver,
10).until(EC.presence_of_element_located((By.CLASS_NAME, 'class')))
items = driver.find_elements_by_class_name('class')
for item in items:
itemList.append(item.text)
return itemList
move_to_next_page()
get_page_data()
昨天,我成功运行了这个脚本几次;隐式等待使我的程序暂停了长达五秒钟,以确保一切正常。但是,我现在正在尝试运行脚本,大约 70% 的时间我收到一条错误消息:
selenium.common.exceptions.StaleElementReferenceException: Message:
stale element reference: element is not attached to the page document
暗示浏览器仍在加载?奇怪的是,我在达到 10 秒的限制之前收到了这条消息。我什至尝试了 20 和 30 秒,但 selenium 仍然崩溃了很多次。为什么 selenium 不会等待至少 10/20/30 秒?
我很确定隐式等待会导致崩溃,因为当我使用显式等待时:
time.sleep(4)
程序每次都运行。
我有我正在寻找的数据,所以我不再需要这个脚本了。只是不能写出不管浏览器加载时间如何都能正常工作的东西,这真的很令人沮丧。
【问题讨论】:
-
您的意思是显式等待 (
WebDriverWait+ExpectedConditions) 还是隐式等待 (webdriver.implicitly_wait())? -
WebDriverWait + ExpectedConditions!
标签: python selenium webdriver wait