如何点击iframe中的元素?

How to click on element within iframe?

我正在尝试使用 Selenium 库在 IE 上进行 Web 自动化。 我要点击的元素有 iframe。

但是,我收到“找不到元素”错误。

我尝试了很多不同的方法。

Sub activeBexIE_Final()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim Perm_bot As New Selenium.IEDriver
    Perm_bot.Get "https://nalcodirect.nalco.com/irj/servlet/prt/portal/prtroot/pcd%213aportal_content%212fcom.sap.pct%212fplatform_add_ons%212fcom.sap.ip.bi%212fiViews%212fcom.sap.ip.bi.bex?BOOKMARK=0O867HQNBT13YLB5Q21HLAL2H", timeout:=1000, Raise:=False

    Perm_bot.Wait 5000

    ' website opening successfully
    Perm_bot.FindElementById("logonuidfield").SendKeys "XYZ@ABC.com"
    Perm_bot.SendKeys Perm_bot.Keys.Tab
    Perm_bot.SendKeys "ABCD"
    Perm_bot.SendKeys Perm_bot.Keys.Enter

    ' the error is element not found at .click line
    Perm_bot.switchToFrame Perm_bot.FindElementByName("iframe_Roundtrip_9223372036563636042")
    Perm_bot.FindElementById("BUTTON_OPEN_SAVE_btn1_acButton").Click

    Perm_bot.Wait 5000

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    perm_dot.Quit
    Set perm_dot = Nothing
End Sub

HTML:

iframe截图:

元素截图:

这可能是因为脚本运行速度快于页面加载速度。您可以在切换到 iframe 之前添加等待时间。此外,可能还有名称为 iframe_Roundtrip_9223372036563636042 的其他元素,因此您可以在搜索 iframe 时使用 FindElementById

我用下面的代码做了一个简单的示例,它可以很好地工作:

Public Sub seleniumtutorial()
    Dim driver As New Selenium.IEDriver
    driver.Get "https://zhouyuzy.github.io/create-test-page/iframe.html  "
    driver.Wait 5000
    driver.SwitchToFrame driver.FindElementById("iframe_Roundtrip_9223372036563636042")
    driver.FindElementById("BUTTON_OPEN_SAVE_btn1_acButton").Click
    driver.Wait 5000
End Sub

结果如下: