vba VBA获取元素的父节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19053724/
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 23:32:15  来源:igfitidea点击:

VBA get parent node of element

htmlvbams-word

提问by gNerb

I have a script that parses an HTML page to find an element with a specified ID. What I need is to get the parent node (actually, I need to go 2 parent nodes up) so that I can either cycle through all the links in the table to find the link I want OR so I can parse the HTML of the entire table to find the link I want.

我有一个脚本,可以解析 HTML 页面以查找具有指定 ID 的元素。我需要的是获取父节点(实际上,我需要向上移动 2 个父节点),以便我可以循环遍历表中的所有链接以找到我想要的链接,或者这样我就可以解析整个 HTML表找到我想要的链接。

Sub testmacro()

'Constants
Const pdlID = "Id of the element"
Const urlbase = "what ever url"

'containers
Dim web As Object
Dim prompt As String
Dim pdlTbl As Object
Dim pdllink As Object


'Get URL
prompt = InputBox("Paste the URL here: ", "URL")

'create IE instance
Set web = CreateObject("InternetExplorer.Application")
web.Visible = True
web.Navigate prompt

Do While web.Busy Or web.ReadyState <> 4
    DoEvents
Loop

'get IE document
Set pdlTbl = web.Document
Set pdlTbl = pdlTbl.getelementbyid(pdlID)

'Get parent node of element

web.Quit
Set web = Nothing

End Sub

Ive tried to find information on getting parent nodes but I couldn't so any help on locating the parent nodes would be great.

我试图找到有关获取父节点的信息,但我无法找到有关定位父节点的任何帮助。

Additionally, I was having major issues trying to cycle through elements in the document. I grabbed many many code samples from this site and they were all returning the same errors "Object does not support this method" or something along the lines. It was highlighing the first line in loops that looked like this.

此外,我在尝试循环浏览文档中的元素时遇到了重大问题。我从该站点获取了许多代码示例,它们都返回相同的错误“对象不支持此方法”或类似的错误。它在看起来像这样的循环中突出显示第一行。

for each a in pdltbl

next a

This error came out no matter which tag I tried to use or the type of element I looked through (pdlID refers to a TD element for reference)

无论我尝试使用哪个标签或我查看的元素类型,都会出现此错误(pdlID 指的是 TD 元素以供参考)

Basically, I just want to be able to search through the table to find a link with a specific URL (based off the url in prompt)

基本上,我只是希望能够搜索表格以找到具有特定 URL 的链接(基于提示中的 url)

采纳答案by Tim Williams

Set pdlTbl = pdlTbl.getelementbyid(pdlID)
Set parentParent = pdlTbl.parentElement.parentElement

to get all the links in a table:

获取表格中的所有链接:

Set allLinks = tbl.getElementsByTagName("a")
For Each a in allLinks
    '...
Next a