Python的硒(等待框架,要素查询) [英] Python Selenium (waiting for frame, element lookups)
问题描述
我有这些包括:
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).
我不知道这是因为硒实际上不是等待它执行code或什么的其余部分之前的页面加载。有没有办法来强制网页加载?
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的硒(等待框架,要素查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!