Selenium WebDriver.wait 不等待 Python

Selenium WebDriver.wait does not wait Python

我想让 Selenium 等待网页加载完成。我在 macOS 10.15.7

上使用 Safari 14.1.2

所以我尝试如下:

// login process and it successes and the following page shows up
login_submit.click() 

// the page after the authorization, make selenium wait until ```hoge``` is clickable
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'hoge')))

此代码未按预期工作。它因错误 selenium.common.exceptions.NoSuchFrameException: 而失败。马上就报错,貌似没有10秒的等待。

堆栈跟踪如下:(路径已修改。)

Traceback (most recent call last):
  File "/login.py", line 99, in <module>
    login_schedule().quit()
  File "/login.py", line 67, in login_schedule
    wait.until(EC.presence_of_element_located((By.ID, 'HOGEHOGE')))
  File "/selenium/webdriver/support/wait.py", line 71, in until
    value = method(self._driver)
  File "/selenium/webdriver/support/expected_conditions.py", line 64, in __call__
    return _find_element(driver, self.locator)
  File "/selenium/webdriver/support/expected_conditions.py", line 415, in _find_element
    raise e
  File "/selenium/webdriver/support/expected_conditions.py", line 411, in _find_element
    return driver.find_element(*by)
  File "/selenium/webdriver/remote/webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchFrameException: Message: 

当我把 time.sleep(10) 改为如下所示时,

import time
// login process and it successes and the following page shows up
login_submit.click() 

time.sleep(10)
// the page after the authorization, make selenium wait until ```hoge``` is clickable
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'hoge')))

它按预期工作。 注意最后一部分甚至可以替换

browser.find_element_by_xpath("//select[@id='hoge']")

我的 Python 代码有什么问题?

尝试使用此功能等待元素或其他内容出现:

def wait_for(xpath):
  while True:
    try:
      driver.find_element_by_xpath(xpath) 
      return True
    except NoSuchElementException:
      continue

别忘了

from selenium.common.exceptions import NoSuchElementException

您可以使用任何不重要的 XPATH 作为方法。