简体   繁体   English

如何在没有 iframe id 的情况下与 IE iframe 交互

[英]How to interact with IE iframe without iframe id

I need to click a div inside an iframe in order to trigger a download.我需要单击 iframe 中的 div 才能触发下载。 I'm having a hard time trying to locate the iframe element as it doesn't have an ID.我很难找到 iframe 元素,因为它没有 ID。 Here is the iframe element:这是 iframe 元素:

<iframe title="data visualization" src="https://sample.com" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowfullscreen="true" style="width: 100%; height: 100%; display: block; visibility: visible;" allowtransparency="true"></iframe>

And this is the div element inside the iframe:这是 iframe 中的 div 元素:

<div tabindex="-1" class="tabToolbarButton tab-widget download" role="button" style="width: 95px; -ms-touch-action: none;" aria-label="Download">
    <span class="tabToolbarButtonImg tab-icon-download"></span>
    <span class="tabToolbarButtonText">Download</span>
</div>

Use one of it's attributes.使用它的属性之一。 For example,例如,

ie.document.querySelector("[title='data visualization']").contentDocument.querySelector(".tabToolbarButtonText").click 'change this end bit for the appropriate element to click

Perhaps也许

ie.document.querySelector("[title='data visualization']").contentDocument.querySelector(".download").click 'change this end bit for the appropriate element to click

Or it's src attribute value direct:或者它的src属性值直接:

ie.Navigate "https://sample.com"

Modern browsers are optimised for css selectors so this method is fast.现代浏览器针对css 选择器进行了优化,因此这种方法速度很快。 Using querySelector also stops at first match which is again an efficiency gain here.使用querySelector也会在第一次匹配时停止,这再次提高了效率。

You could also try to use the getElementsbyTagName method to get the Iframe first, then, according to the Iframe.contentDocument property to get the elements via the class Name.您也可以尝试使用 getElementsbyTagName 方法先获取 Iframe,然后根据 Iframe.contentDocument 属性通过 class 名称获取元素。

Sample code as below:示例代码如下:

Sub Test()
    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate "<the website url>"

        While ie.readyState <> 4
            DoEvents
        Wend

        ie.Document.getElementsbyTagName("iframe")(0).contentDocument.getElementsbyClassName("tabToolbarButton tab-widget download")(0).Click
    End With
    Set ie = Nothing
End Sub

[Note] Please note the element's index when you are using the getElementsbyTagName and getElementsbyClassName. [注意] 使用getElementsbyTagName 和getElementsbyClassName 时请注意元素的索引。 It is starting from 0.它从 0 开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM