【问题标题】:Selenium WebDriver.wait does not wait PythonSelenium WebDriver.wait 不等待 Python
【发布时间】:2021-09-13 04:37:33
【问题描述】:

我想让 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 s 的等待。

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

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 代码有什么问题?

【问题讨论】:

  • 你确定没有框架吗?另外,你可以试试这个visibility_of_element_located 像这样:WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.ID, 'hoge'))).click()
  • 其实我不确定...但是正如我所写,它在等待 10 秒后可以正常工作(没有帧异常).. 我尝试了visibility,结果几乎与以前相同一。
  • 网页链接可以分享吗?
  • hmm.. 如前所述 Safari 有 bug,你可以切换到 chrome 或 gecko
  • 应该是最好的选择.. 还好没有浏览器限制.. 非常感谢!

标签: python selenium selenium-webdriver safari webdriver


【解决方案1】:

尝试使用此功能等到元素或其他东西出现:

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 作为方法。

【讨论】:

  • 谢谢我会用的
猜你喜欢
  • 2018-02-04
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 2021-05-23
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多