Python Selenium(等待框架、元素查找)

标签 python selenium automation frames

我有这些包括:

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")

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

最佳答案

你可以使用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"))

关于Python Selenium(等待框架、元素查找),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827150/

相关文章:

python - Django 表单中的可编辑选择字段/下拉框

Python:我如何使用 itertools?

python - 将不同的参数传递给 Fabric 中的不同主机

python - 将两个 Pandas 数据帧与仅添加整数计数相结合

python - 单击来自 gmail 收件箱 Python 的特定电子邮件

java - 从 Jenkins 运行 JunitCore.runClasses

java - Selenium 无法通过 id 找到元素

windows - 当用户没有足够的权限时隐藏 COM-Server OLE 错误消息

git - 使用 Actions 在测试通过后自动 merge ?

使用 USB 连接到我的计算机的手机的 Android 测试自动化