Python Selenium切换到iframe中的iframe [英] Python Selenium switch into an iframe within an iframe

查看:1497
本文介绍了Python Selenium切换到iframe中的iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Selenium,Python和BS4访问iframe中的iframe

I am trying to access an iframe within an iframe using Selenium, Python, and BS4

from bs4 import BeautifulSoup
from selenium import webdriver
import time
import html5lib

driver = webdriver.Firefox()
driver.implicitly_wait(10)

driver.get('http://myurl.com')
try:
    time.sleep(4)
    iframe = driver.find_elements_by_tag_name('iframe')[0]
    driver.switch_to_default_content()

    driver.switch_to_frame(iframe)
    driver.switch_to_default_content()
    driver.find_elements_by_tag_name('iframe')[0]

    output = driver.page_source

    print output

finally:
    driver.quit();

在返回的文本中,似乎还有两个iframe。我该如何访问这些?我在上面的代码中尝试过没有成功。

Within the returned text, there appears to be two more iframes. How would I access those? I have attempted in the code above without success.

感谢任何帮助。

推荐答案

switch_to_default_content()将返回到文档的顶部。发生的事情是你切换到第一个 iframe ,切换回文档的顶部,然后试图找到第二个 iframe 。 Selenium无法找到第二个 iframe ,因为它位于第一个 iframe 内。

switch_to_default_content() will return you to the top of the document. What was happening is you switched into the first iframe, switched back to the top of the document, then tried to find the second iframe. Selenium can't find the second iframe, because it's inside of the first iframe.

如果你删除第二个 switch_to_default_content()你应该没问题:

If you remove the second switch_to_default_content() you should be fine:

iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_default_content()

driver.switch_to_frame(iframe)
driver.find_elements_by_tag_name('iframe')[0]

这篇关于Python Selenium切换到iframe中的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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