【问题标题】:Python Selenium (waiting for frame, element lookups)Python Selenium(等待帧,元素查找)
【发布时间】:2012-04-07 01:44:55
【问题描述】:

我有这些包括:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

浏览器设置通过

browser = webdriver.Firefox() 
browser.get(loginURL) 

但有时我会这样做

browser.switch_to_frame("nameofframe")

而且它不起作用(有时会,有时不会)。

我不确定这是否是因为 Selenium 在执行其余代码之前实际上并没有等待页面加载或什么。有没有办法强制网页加载?

因为有时我会做类似的事情

browser.find_element_by_name("txtPassword").send_keys(password + Keys.RETURN)
#sends login information, goes to next page and clicks on Relevant Link Text
browser.find_element_by_partial_link_text("Relevant Link Text").click()

它在大多数情况下都能很好地工作,但有时我会收到一个错误,即它无法找到“相关链接文本”,因为它无法“看到”它或其他类似的东西。

另外,有没有更好的方法来检查元素是否存在?也就是最好的处理方式是什么:

browser.find_element_by_id("something")

该元素何时可能存在或可能不存在?

【问题讨论】:

  • 我应该补充一点,元素东西在找不到东西时会引发错误。您通常对所有 find_element 命令都使用 try/except 吗?
  • 不允许转发。如果您想引起注意,请阅读faq中的此部分。
  • 阅读this

标签: python selenium automation frames


【解决方案1】:

你可以使用WebDriverWait:

from contextlib import closing
from selenium.webdriver import Chrome as Browser
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchFrameException


def frame_available_cb(frame_reference):
    """Return a callback that checks whether the frame is available."""
    def callback(browser):
        try:
            browser.switch_to_frame(frame_reference)
        except NoSuchFrameException:
            return False
        else:
            return True
    return callback

with closing(Browser()) as browser:
    browser.get(url)
    # wait for frame
    WebDriverWait(browser, timeout=10).until(frame_available_cb("frame name"))

【讨论】:

  • +1。显式/隐式等待是最可靠的解决方案。
  • 我需要在 browser.get(url) 之后添加一个 browser.implicitly_wait(5)
猜你喜欢
  • 2016-09-28
  • 1970-01-01
  • 2016-12-29
  • 2014-03-05
  • 2014-05-07
  • 2013-08-14
  • 1970-01-01
  • 2014-11-09
  • 2020-06-12
相关资源
最近更新 更多