【发布时间】: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,真可惜。
【问题讨论】: