在 VBA 中获取属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8213850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:30:59  来源:igfitidea点击:

Getting attribute values in VBA

domvbaaccess-vbagetelementsbytagname

提问by Patrick Villela

I need to make a VBA file that will read a webpage and return the value of the SRC attribute of the IMG tag. I wasn't able to make the last step work. Can you guys help me?

我需要制作一个 VBA 文件来读取网页并返回 IMG 标签的 SRC 属性的值。我无法使最后一步起作用。你们能帮帮我吗?

<html>
<body>
<img src="image.jpg">
</body>
</html>

===Edit=== I managed to return the attribute object. Now I need to return its value

===编辑=== 我设法返回了属性对象。现在我需要返回它的值

Option Compare Database

Sub AcessaPagina()
    Dim ie As InternetExplorer
    Dim test As String
    Dim obj As Object

    Set ie = New InternetExplorer
    ie.Navigate "http://www.google.com.br"
    MsgBox ie.Document.getElementsByTagName("img").Item(0).Attributes("src")
    ie.Visible = True 
End Sub

That's what I have at the moment.

这就是我目前所拥有的。

回答by JimmyPena

There is no method called "getElementByTagName" -- it's called getElementsByTagName(note the sbecause it is a collection)

没有名为“getElementByTagName”的方法——它被称为getElementsByTagName(注意s,因为它是一个集合)

The Document Object returns a collection of all the img tags in the source. So you can iterate it like this:

文档对象返回源中所有 img 标签的集合。所以你可以像这样迭代它:

Sub AcessaPagina()
    Dim ie As Object ' InternetExplorer
    Dim images As Object ' MSHTML.IHTMLElementCollection
    Dim image As Object ' MSHTML.IHTMLElement

    Set ie = CreateObject("InternetExplorer.Application")
    ie.navigate "http://www.google.com.br"
    Set images = GetAllImages(ie)

    For Each image In images
      Debug.Print image.getAttribute("src")
    Next image

End Sub

Function GetAllImages(ie As Object) As Object
  Set GetAllImages = ie.document.images
End Function