通常您可以使用Ctrl+U 在浏览器中查看源HTML,然后您可以使用Ctrl+F 搜索任何文本,即。 iframe。但是Ctrl+U 提供了来自服务器的原始 HTML,而没有 JavaScript 添加的元素。但大多数情况下iframe 是原始 HTML,并且这种方法有效。
但如果页面使用 JavaScript 来添加 iframe,那么您可能需要在 Firefox/Chrome 中添加 DevTools 才能看到包含所有添加元素的 HTML。
你也可以使用 Selenium 来检查是否有iframe - 即。
driver.find_elements_by_tag_name('iframe')
但如果页面使用 JavaScript 添加 iframe 则可能需要等待新元素。
你可以使用原始但容易记住
time.sleep(seconds)
或Selenium 具有检查元素是否在页面上的方法 - 请参阅文档Waits。
因为找不到元素时可能会报错,所以需要try/except,代码比较长。
wait = WebDriverWait(driver, 5)
try:
wait.until(EC.presence_of_element_located((By.TAG_NAME, "iframe")))
except Exception as ex:
#print(ex)
print('len(all_iframes): 0')
顺便说一句:它可以使用selenium.common.exceptions.TimeoutException而不是Exception,但它更难记住所以我在这里跳过它。
此代码使用time.sleep() 等待。
顺便说一句:要切换到下一个iframe,你必须先回到主框架。如果不切换,它可能会在当前iframe 中搜索下一个iframe。
import selenium.webdriver
import time
url = 'https://mail.protonmail.com/create/new?language=en'
driver = selenium.webdriver.Firefox()
driver.get(url)
time.sleep(5) # JavaScript may need some time to add all elements
all_iframes = driver.find_elements_by_tag_name('iframe')
print('len(all_iframes):', len(all_iframes))
for number, frame in enumerate(all_iframes):
print('--- frame:', number, '---')
# switch to iframe
driver.switch_to.frame(frame)
# search buttons in iframe
all_buttons = driver.find_elements_by_tag_name('button')
print('len(all_buttons):', len(all_buttons))
# go back to main frame
driver.switch_to.default_content()
结果:
len(all_iframes): 2
--- frame: 0 ---
len(all_buttons): 0
--- frame: 1 ---
len(all_buttons): 1
编辑:
带有WebDriverWait 的版本,但它也需要等待buttons,因为它不会等待整整5 秒,而是在找到iframes 时立即尝试搜索buttons,但JavaScript 可能还需要时间在iframe中添加按钮
import selenium.webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#import time
url = 'https://mail.protonmail.com/create/new?language=en'
driver = selenium.webdriver.Firefox()
driver.get(url)
#time.sleep(5) # JavaScript may need time to add all elements
wait = WebDriverWait(driver, 5)
try:
wait.until(EC.presence_of_element_located((By.TAG_NAME, "iframe")))
except Exception as ex:
#print(ex)
print('len(all_iframes): 0')
all_iframes = driver.find_elements_by_tag_name('iframe')
print('len(all_iframes):', len(all_iframes))
for number, frame in enumerate(all_iframes):
print('--- frame:', number, '---')
# switch to iframe
driver.switch_to.frame(frame)
try:
wait.until(EC.presence_of_element_located((By.TAG_NAME, "button")))
all_buttons = driver.find_elements_by_tag_name('button')
print('len(all_buttons):', len(all_buttons))
except Exception as ex:
#print(ex)
print('len(all_buttons): 0')
# go back to main frame
driver.switch_to.default_content()