如何使用 VBA excel 从资源中获取 og:image

bpy*_*bpy 4 excel vba excel-2007

我如何og:image从资源中获取VBA excel 2007

例如,这个网址:

https://www.bbc.com/reel/video/p08jgfdg/the-truth-about-christopher-columbus
Run Code Online (Sandbox Code Playgroud)

Dec*_*urn 5

使用更新版本的 Excel,您可以尝试以下操作:

Sub GetImageFromHead()

    Dim MyUrl As String
    MyUrl = "https://www.bbc.com/reel/video/p08jgfdg/the-truth-about-christopher-columbus"

    'Required library reference: Microsoft XML v6.0
    Dim HttpRequest As MSXML2.XMLHTTP60
    Set HttpRequest = New MSXML2.XMLHTTP60
    HttpRequest.Open "GET", MyUrl, False
    HttpRequest.Send
    
    Dim HtmlDoc As Object
    Set HtmlDoc = CreateObject("htmlfile")
    HtmlDoc.Write HttpRequest.responseText

    'This next line makes sure that the JavaScript on the page gets processed before continuing execution of the code.
    DoEvents 

    'Required library reference: Microsoft HTML Object
    Dim MetaCollection As MSHTML.IHTMLElementCollection
    Set MetaCollection = HtmlDoc.getElementsByTagName("meta")
    
    Dim HtmlElement As MSHTML.IHTMLElement
    For Each HtmlElement In MetaCollection
        If HtmlElement.getAttribute("property") = "og:image" Then
            ActiveSheet.Pictures.Insert (HtmlElement.getAttribute("content"))
        End If
    Next

End Sub
Run Code Online (Sandbox Code Playgroud)

但是由于您的问题是针对 Excel 2007,您必须改为这样定义HttpRequest

    'Required library reference: Microsoft XML v3.0 or v5.0
    Dim HttpRequest As MSXML2.XMLHTTP
    Set HttpRequest = New MSXML2.XMLHTTP
Run Code Online (Sandbox Code Playgroud)

如果您想要一个只将 URL 作为字符串返回的函数,您可以轻松编辑 Sub 过程,使其成为一个将 MyUrl 作为参数并返回字符串而不是使用它在 Activesheet 中插入图像的函数(像这样例如)。

  • @bpy – 如果你告诉我运行时错误代码,也许我可以提供帮助。不过,由于我没有Excel 2007,所以测试起来有点困难。关于函数形式,你当然可以使用`MyUrl`作为参数来做到这一点,但是你希望函数返回什么?图像 URL 作为字符串? (3认同)
  • @bpy – 我刚刚意识到你的问题有“Excel-2007”标签。我添加了一些内容,使其适用于该版本的 Excel。 (2认同)
  • @bpy – 让我们将此讨论带到[聊天](https://chat.stackoverflow.com/rooms/220384/my-room)。 (2认同)