首页 > 解决方案 > 如何在 Python (Selenium) 中处理动态 iFrame ID

问题描述

我有一个要切换到的 iFrame,但 iFrame 每次都会生成一个随机 ID。如何切换到此 iFrame。据我所知,资源保持一致。

更新:点击下载它有效,但点击关闭它没有。

<iframe id="e674" src="/resource.ashx/636625958320000000/du/webviewer/html5/Reader.html?setLng=en#d=%2Fdocumentviewer.ashx%2FDownloadDocument%3FstateId%3Dv3x4o%26cacheInfoKey%3D1arhoq9%2F1arhoq9-1o5aabb.json&amp;auto_load=false&amp;languageUrl=%2Fresource.ashx%2F636625958320000000%2Fdu%2Flocalization.json%3Fdisplay%3D__lng__&amp;custom=%7B%22permissions%22%3A65535%2C%22showToolbar%22%3Atrue%2C%22showSidePane%22%3Atrue%2C%22singlePageRotation%22%3Afalse%2C%22downloadUrl%22%3A%22%2Fdocumentviewer.ashx%2FDownloadSource%3FstateId%3Dv3x4o%26cacheInfoKey%3D1arhoq9%2F1arhoq9-1o5aabb.json%22%2C%22downloadAsPdfUrl%22%3A%22%2Fdocumentviewer.ashx%2FDownloadAsPdf%3FstateId%3Dv3x4o%26cacheInfoKey%3D1arhoq9%2F1arhoq9-1o5aabb.json%22%7D&amp;filepicker=0&amp;preloadWorker=1&amp;pdfnet=0&amp;pageHistory=1&amp;subzero=1" frameborder="0" width="100%" height="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>


driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@name='rwDocumentviewer']"))

                time.sleep(3)

                driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'webviewer/html5/Reader.html')]"))

                #Click on download
                downloadButton = driver.find_element_by_xpath('//*[@id="downloadButton"]')
                downloadButton.click()

                time.sleep(3)

                #Click on close
                closeButton = driver.find_element_by_xpath('//*[@id="btnZorgAnnuleren"]')
                closeButton.click()            

                driver.switch_to.default_content()

标签: pythonselenium

解决方案


看看这是否有效:

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@name='rwDocumentviewer']"))

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'webviewer/html5/Reader.html')]"))

推荐阅读