如何正确等待python-selenium中的框架可用?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何正确等待python-selenium中的框架可用?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2783字,纯文字阅读大概需要4分钟。
内容图文
![如何正确等待python-selenium中的框架可用?](/upload/InfoBanner/zyjiaocheng/707/63865e4d0fd04a4b9dc356cb19827259.jpg)
我有一个相当复杂的网页设置我需要测试,包含嵌套框架.
在实际问题中,selenium代码正在加载包含框架的新网页内容,我想切换到该框架.为了避免任何明确的等待,我尝试了以下代码片段:
self.driver.switch_to_default_content()
WebDriverWait(self.driver, 300). until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'frame1')))
WebDriverWait(self.driver, 300). until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'frame2')))
但是,此代码段始终失败并导致以下错误:
...
File "/home/adietz/Projects/Venv/nosetests/local/lib/python2.7/site-packages/selenium/webdriver/support/wait.py", line 71, in until
value = method(self._driver)
File "/home/adietz/Projects/Venv/nosetests/local/lib/python2.7/site-packages/selenium/webdriver/support/expected_conditions.py", line 247, in __call__
self.frame_locator))
File "/home/adietz/Projects/Venv/nosetests/local/lib/python2.7/site-packages/selenium/webdriver/support/expected_conditions.py", line 402, in _find_element
raise e
WebDriverException: Message: TypeError: can't access dead object
但是,如果我另外使用睡眠:
time.sleep(30)
self.driver.switch_to_default_content()
WebDriverWait(self.driver, 300). until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'frame1')))
WebDriverWait(self.driver, 300). until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'frame2')))
selenium能够找到框架内的框架并切换到它.看起来在错误的情况下,selenium切换到’frame1’而’frame2’尚未加载,但’frame2’被加载到’frame1’的某个其他实例中,或者selenium无法识别(可能是bug?).所以现在selenium在某个’frame1’里面,并且由于某些原因没有意识到’frame2’已被加载.
我可以解决这个问题的唯一方法(不使用长时间睡眠)就是使用这段丑陋的代码:
mustend = time.time() + 300
while time.time() < mustend:
try:
self.driver.switch_to_default_content()
self.driver.switch_to.frame(self.driver.find_element_by_id("frame1"))
self.driver.switch_to.frame(self.driver.find_element_by_id("frame2"))
break
except WebDriverException as e:
self.log("Sleeping 1 sec")
time.sleep(1)
if time.time() > mustend:
raise TimeoutException
因此,每当我得到一个WebDriverException(死对象)时,我会转到顶层框架并尝试逐帧切换到内部框架.
我可以尝试其他方法吗?
附加信息
> iframe是嵌套的,即’frame2’在’frame1’内.
解决方法:
更好的方法是制作自己的expected_condition.
例如:
class nested_frames_to_be_available_and_switch:
def __init__(self, *args):
"""
:param args: locators tuple of nested frames (BY.ID, "ID1"), (BY.ID, "ID2"), ...
"""
self.locators = args
def __call__(self, driver):
try:
for locator in self.locators:
driver.switch_to.frame(driver.find_element(*locator))
except WebDriverException:
driver.switch_to_default_content()
return False
return True
WebDriverWait(driver, 300).until(nested_frames_to_be_available_and_switch((By.ID, 'frame1'), (By.ID, 'frame1')))
但也许没有必要..告诉我所以我需要看到你的HTML DOM.
内容总结
以上是互联网集市为您收集整理的如何正确等待python-selenium中的框架可用?全部内容,希望文章能够帮你解决如何正确等待python-selenium中的框架可用?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。