Getting attribute values in VBA

一世执手 提交于 2020-01-02 08:24:55

问题


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?

<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.


回答1:


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

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

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


来源:https://stackoverflow.com/questions/8213850/getting-attribute-values-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!