我正在尝试切换到框架,但Selenium无法找到该元素。 这是我在定位之前通过Selenium获得的HTML代码:
<div class="jqmPopOverlay" style="height: 100%; width: 100%; position: fixed; left: 0px; top: 0px; z-index: 2999; opacity: 0.7;"></div><div class="login login-main jqmID1" id="loginForm" style="z-index: 3000; top: 0px; left: 319.5px; display: block;">
<div class="titlebar">
<a class="close" href="#" tabindex="7">✕</a>
</div>
<div class="tooltipstered" id="loginFrame"><iframe frameborder="0" id="easyXDM_default127_provider" name="easyXDM_default127_provider" scrolling="no" style="height: 509.667px;" width="100%"></iframe></div>
</div>
<script async="" defer="" type="text/javascript">undefined</script><script async="" src="//www.googleadservices.com/pagead/conversion_async.js" type="text/javascript"></script><script async="" src="https://www.google-analytics.com/plugins/ua/ec.js" type="text/javascript"></script><script async="" src="https://www.google-analytics.com/analytics.js" type="text/javascript"></script><script async="" src="//www.googletagmanager.com/gtm.js?id=GTM-4DBM"></script><script type="text/javascript">
这是Python代码:
browser = webdriver.Chrome('chromedriver.exe')
browser.get(url)
frame = browser.find_element_by_id("easyXDM_default6255_provider")
browser.switch_to_frame(frame)
这是错误:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"easyXDM_default6255_provider"}
(Session info: chrome=67.0.3396.99)
(Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64)
如您所见,HTML中有元素,但是找不到它。 我在做什么错了?
答案 0 :(得分:1)
尝试一下:
browser = webdriver.Chrome('chromedriver.exe')
browser.get(url)
WebDriverWait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//*[@id = 'loginFrame']/iframe")))
注意: ,您必须添加一些导入:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
首先,您的框架可能具有通用ID和名称。这就是为什么我提出了另一个选择器。其次,我添加了WebDriverWait
,它会等待至少10秒钟,直到帧可用,然后才切换到该帧。
PS: :在iframe中处理完内容后,请不要忘记切换到默认内容,例如:
browser.switch_to.default_content()
否则,您将无法与整个DOM交互。