【问题标题】:Read and manipulate HTML with Excel VBA使用 Excel VBA 读取和操作 HTML
【发布时间】:2016-11-26 17:06:53
【问题描述】:

假设我有一个页面如下,保存在 c:\temp\html_page.html:

<html>
   <head>
      <link rel="stylesheet" href="styles.css">
   </head>
   <body>
      <div id="xxx1">
         <img src="test.png">
      </div>
   </body>
</html>

我想根据 Excel 数据和 VBA 以编程方式调整 img 的 src 属性。基本上是一种使用 Xpath 查找 div 并调整其中包含的(单个)img 标签的方法。

我找到了一个通过 XML 库 here 使用 VBA 操作 XML 的示例,但我一直在努力使这项工作与 HTML 对象库一起工作;找不到任何示例和/或文档。

Dim XDoc As Object, root As Object

Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False

If XDoc.Load(html_path) Then
    Debug.Print "Document loaded"
Else
    Dim strErrText As String
    Dim xPE As MSXML2.IXMLDOMParseError
    ' Obtain the ParseError object
    Set xPE = XDoc.parseError
    With xPE
       strErrText = "Your XML Document failed to load" & _
         "due the following error." & vbCrLf & _
         "Error #: " & .ErrorCode & ": " & xPE.reason & _
         "Line #: " & .Line & vbCrLf & _
         "Line Position: " & .linepos & vbCrLf & _
         "Position In File: " & .filepos & vbCrLf & _
         "Source Text: " & .srcText & vbCrLf & _
         "Document URL: " & .URL
    End With
    MsgBox strErrText, vbExclamation

我想做的就是:

'...
Set outer_div = XDoc.SelectFirstNode("//div[id='xxx1'")
... edit the img attribute

但我无法加载 HTML 页面,因为它不是正确的 XML(img 标记未关闭)。

非常感谢任何帮助。哦,我不能使用其他语言,比如 Python,真可惜。

【问题讨论】:

    标签: html vba excel


    【解决方案1】:

    这不是你想要的,但它可能已经足够接近了。不要使用XML 库,而是使用HTML 库:

    Sub changeImg()
    
        Dim dom As Object
        Dim img As Object
        Dim src As String
    
        Set dom = CreateObject("htmlFile")
    
        Open "C:\temp\test.html" For Input As #1
            src = Input$(LOF(1), 1)
        Close #1
    
        dom.body.innerHTML = src
    
        Set img = dom.getelementsbytagname("img")(0)
    
        img.src = "..."
    
        Open "C:\temp\test.html" For Output As #1
            Print #1, dom.DocumentElement.outerHTML
        Close #1
    
    
    End Sub
    

    问题是生成的文件将添加Head 节点,并且标签名称为大写。如果您能忍受这一点,那么该解决方案将为您工作。

    顺便说一句,如果你想更深入地做一些事情,更好的选择器考虑早期绑定。暴露的 HTML 界面与后期绑定时的界面不同,并且支持更多属性 - 您需要添加对 HTML Object Library 的引用:

    Sub changeImg()
    
        Dim dom As HTMLDocument
        Dim img As Object
        Dim src As String
    
        Set dom = CreateObject("htmlFile")
    
        Open "C:\temp\test.html" For Input As #1
            src = Input$(LOF(1), 1)
        Close #1
    
        dom.body.innerHTML = src
    
        Set img = dom.getelementsbytagname("img")(0)
    
        img.src = "..."
    
        Open "C:\temp\test.html" For Output As #1
            Print #1, dom.DocumentElement.outerHTML
        Close #1
    
    
    End Sub
    

    【讨论】:

    • 非常感谢!好像我快到了:这个问题不是 100% 准确的。我正在寻找适用于多行 HTML 文件的解决方案。我试图找到如何调整代码,但还没有成功。您介意将其添加到答案中吗?
    • @MattV,抱歉,我一定遗漏了一些东西,为什么这不适用于多行文件?告诉我,我会更新
    【解决方案2】:

    为此,您可以使用doc.querySelector("div[id='xxx1'] img")。要更改src 属性,请使用img.setAttribute "src", "new.png"。高温

    Option Explicit
    
    ' Add reference to Microsoft Internet Controls (SHDocVw)
    ' Add reference to Microsoft HTML Object Library
    
    Sub Demo()
        Dim ie As SHDocVw.InternetExplorer
        Dim doc As MSHTML.HTMLDocument
        Dim url As String
    
        url = "file:///C:/Temp/StackOverflow/html/html_page.html"
        Set ie = New SHDocVw.InternetExplorer
        ie.Visible = True
        ie.navigate url
        While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
        Set doc = ie.document
    
        Dim img As HTMLImg
        Set img = doc.querySelector("div[id='xxx1'] img")
        If Not img Is Nothing Then
            img.setAttribute "src", "new.png"
        End If
        ie.Quit
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      相关资源
      最近更新 更多