Python 硒:Can';t定位元素
我试图切换到帧,但Selenium找不到元素。 以下是我在查找之前使用Selenium获得的HTML代码:Python 硒:Can';t定位元素,python,selenium,iframe,Python,Selenium,Iframe,我试图切换到帧,但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="login
<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">
以下是错误:
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中有元素,但它无法定位。
我做错了什么?试试这个:
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交互。这可能是因为页面上没有加载元素。您正在按ID“easyXDM\u default6255\u provider”搜索框架,但如果您检查HTML,则没有具有此ID的元素。。。。看看我的答案:看起来每次id都是随机生成的…检查元素是否有动态id/名称
browser.switch_to.default_content()