python - 使用 Python + Selenium 选择 iframe

标签 python selenium xpath iframe css-selectors

所以,我对如何在 Selenium 中做到这一点感到非常困惑,并且无法在任何地方找到答案,所以我分享我的经验。

我试图选择一个 iframe 并且没有运气(或者无论如何都不能重复)。 HTML 是:

<iframe id="upload_file_frame" width="100%" height="465px" frameborder="0" framemargin="0" name="upload_file_frame" src="/blah/import/">
<html>
    <body>
        <div class="import_devices">
            <div class="import_type">
                <a class="secondary_button" href="/blah/blah/?source=blah">
                    <div class="import_choice_image">
                        <img alt="blah" src="/public/images/blah/import/blah.png">
                    </div>
                    <div class="import_choice_text">Blah Blah</div>
                </a>
            </div>
        </div>
    </body>
</html>

Python 代码(使用 selenium 库)试图通过以下方式找到这个 iframe:

    @timed(650)
def test_pedometer(self):
    sel = self.selenium
    ...
    time.sleep(10)
    for i in range(5):
        try:
            if sel.select_frame("css=#upload_file_frame"): break
        except: pass
        time.sleep(10)
    else: self.fail("Cannot find upload_file_frame, the iframe for the device upload image buttons")

我能找到的所有 Selenium 命令组合都重复失败。

偶尔的成功是不可复制的,所以也许是某种竞争条件或什么?从来没有找到正确的方法将它放入 Selenium 中。

最佳答案

在使用 iframe 进行测试并尝试在 iframe 中插入数据时,这对我使用 Python (v. 2.7)、webdriver 和 Selenium 有效:

self.driver = webdriver.Firefox()

## Give time for iframe to load ##
time.sleep(3)
## You have to switch to the iframe like so: ##
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
## Insert text via xpath ##
elem = driver.find_element_by_xpath("/html/body/p")
elem.send_keys("Lorem Ipsum")
## Switch back to the "default content" (that is, out of the iframes) ##
driver.switch_to.default_content()

关于python - 使用 Python + Selenium 选择 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7534622/

相关文章:

python - 使用 shell=True 参数运行 python 子进程

python - 如何使用 Python 按比例分配日期

python - Hmmlearn分类用法

python - 将 React 应用程序的构建包含到 Flask 中的正确方法

javascript - Selenium Webdriverjs (javascript) 与 chrome

python - 捆绑一个独立的exe

C# 奇怪的问题 - 无法从右到左变量赋值

c# - 在 C# 中使用 Selenium Webdriver,如何选择要写入的文本框,然后写入其中?

python - Scrapy 和 XPath 通用选择

c - 如何用 Libxml2 解析 XML 空节点?在 C 中