Selenium: Can't locate element

China☆狼群 提交于 2021-01-27 17:25:36

问题


I am trying to switch to frame but Selenium can't locate the element. Here is HTML code which I get with Selenium before locating:

<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">     

Here is Python code:

browser = webdriver.Chrome('chromedriver.exe') 
browser.get(url)
frame = browser.find_element_by_id("easyXDM_default6255_provider")
browser.switch_to_frame(frame)

Here is the error:

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)

As you can see there is the element in HTML, but it can't be located. What am I doing wrong?


回答1:


Try this:

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")))

Note: you have to add some imports:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

Firstly, your frame probably has generic id and name. That's why I have proposed another selector. Secondly I have added WebDriverWait, which waits at least 10 seconds until frame will be available and only then switches to it.

PS: when you are done with content inside iframe, don't forget to switch to default content like this:

browser.switch_to.default_content()

otherwise you will be not able to interact with the whole DOM.



来源:https://stackoverflow.com/questions/51515221/selenium-cant-locate-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!