Python Selenium(等待帧,元素查找) [英] Python Selenium (waiting for frame, element lookups)

查看:39
本文介绍了Python Selenium(等待帧,元素查找)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些包括:

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

它不起作用(有时起作用,有时不起作用).

And it won't work (sometimes it does, sometimes it doesn't).

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

I am not sure if this is because Selenium isn't actually waiting for pages to load before it executes the rest of the code or what. Is there a way to force a webpage load?

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

Because sometimes I'll do something like

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

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

And it'll work great most of the time, but sometimes I'll get an error where it can't find "Relevant Link Text" because it can't "see" it or some other such thing.

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

Also, is there a better way to check if an element exists or not? That is, what is the best way to handle:

browser.find_element_by_id("something")

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

When that element may or may not exist?

推荐答案

你可以使用 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(等待帧,元素查找)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆