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

Joh*_*ith 4 python selenium automation frames

我有这些包括:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
Run Code Online (Sandbox Code Playgroud)

浏览器设置通过

browser = webdriver.Firefox() 
browser.get(loginURL) 
Run Code Online (Sandbox Code Playgroud)

但有时我会

browser.switch_to_frame("nameofframe")
Run Code Online (Sandbox Code Playgroud)

并且它不起作用(有时它会,但有时它不会).

我不确定这是不是因为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()
Run Code Online (Sandbox Code Playgroud)

并且它在大多数情况下都会很好用,但有时我会在找不到"相关链接文本"时出错,因为它无法"看到"它或其他类似的东西.

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

browser.find_element_by_id("something")
Run Code Online (Sandbox Code Playgroud)

当该元素可能存在还是不存在?

jfs*_*jfs 9

你可以使用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"))
Run Code Online (Sandbox Code Playgroud)