Python Selenium 切换到 iframe 内的 iframe [英] Python Selenium switch into an iframe within an 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屋!