切换到iframe之后,无法与iframe进行交互Python / Selenium

时间:2020-08-14 17:48:00

标签: python selenium button xpath iframe

我正在尝试与具有以下结构的页面上的按钮进行交互。感兴趣的按钮位于iframe主体中的div内,该主体位于主体内部。我已经阅读了有关如何切换到iframe的所有stackoverflow问题-如下所示,我对此没有任何疑问。我有一个问题是,无论提出什么建议,我都无法与切换到的iframe进行交互。

<!doctype html>
<html ng-app="someApp" xmlns="http://www.w3.org/1999/html">
    <head>
        <script>a lot of scripts</script>
    </head>
    <body class="unwantedBody">
        <iframe> some iframes</iframe>
        <div> different divs </div>
        <main> 
            some content
            <iframe> multiple iframes on different nested levels </iframe>
        </main>
        <div> more divs </div>
        <script> more scripts </script>
        <div id='interesting div'>
            <iframe src="uniqueString">
                <!doctype html>
                #document
                <html>
                    <body>
                        <div>
                            <button id='bestButton'>
                                'Nice title'
                            </button>
                        </div>
                    </body>
                </html>
            </iframe>
        </div>
    </body>
</html>

使用Jupyter Notebook,我已经能够找到iframe并切换到它。该问题与尝试与iFrame交互速度过快无关,因为我可以控制速度。我已经尝试过使用“预期”条件,并等到可以将iframe切换到该条件,但这与我的问题无关。

driver.switch_to.default_content # Making sure no other frame is selected
iframe = driver.find_element_by_xpath("//iframe[contains(@src, 'uniqueString')]")
driver.switch_to.frame(iframe)
print(iframe.get_attribute('id'))

上面的代码打印出“有趣的div”,因此它成功找到了iframe所在的div,并且显然选择了div?然后,我尝试像这样解析iframe:

bestButton = driver.find_element_by_xpath("//button[@id = 'bestButton']")
bestButton.click()

出现错误:

消息:元素不可交互

我还尝试使用上述switch_to.frame(iframe)切换到iframe中的主体 后,因此在此示例中,驱动程序已位于iframe中:

document = driver.find_element_by_xpath('//html/body')
info = document.get_attribute('class')
print(info)

这将打印出来

不需要的身体

因此,驱动程序没有以某种方式切换到我指定的iFrame,而是仍然停留在主HTML上。在chrome上加载网页时,我可以仅使用此xpath // button [contains(@ id ='bestButton')]找到我想要的按钮,但在Selenium中它不起作用,因为它被#document中的iframe。

我想念什么?如果有帮助,我感兴趣的iFrame实际上是一个有关Cookie同意的模式窗口,我试图摆脱与网站交互的方式。

0 个答案:

没有答案