我一直在玩弄使用VBS/VBA从网页上抓取数据。在HTMLElement上使用getElementById而不是HTMLDocument
如果是Javascript,我会远离它,但它在VBS/VBA中看起来并不那么直截了当。
这是我为一个答案做的一个例子,它的工作原理,但我曾计划使用getElementByTagName
访问子节点,但我无法弄清楚如何使用它们! HTMLElement
对象没有这些方法。
Sub Scrape()
Dim Browser As InternetExplorer
Dim Document As HTMLDocument
Dim Elements As IHTMLElementCollection
Dim Element As IHTMLElement
Set Browser = New InternetExplorer
Browser.navigate "http://www.hsbc.com/about-hsbc/leadership"
Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Set Document = Browser.Document
Set Elements = Document.getElementsByClassName("profile-col1")
For Each Element in Elements
Debug.Print "[ name] " & Trim(Element.Children(1).Children(0).innerText)
Debug.Print "[ title] " & Trim(Element.Children(1).Children(1).innerText)
Next Element
Set Document = Nothing
Set Browser = Nothing
End Sub
我一直在寻找的HTMLElement.document
性能,看它是否是像文件的一个片段,但其无论是困难的工作,或只是心不是我所想的
Dim Fragment As HTMLDocument
Set Element = Document.getElementById("example") ' This works
Set Fragment = Element.document ' This doesn't
这也似乎是一个啰嗦的方式来做到这一点(虽然这通常是vba imo的方式)。 任何人都知道是否有一种更简单的方法来链接功能?
Document.getElementById("target").getElementsByTagName("tr")
将是真棒......
我给一个去,我想类似的东西,浏览到我的网页,然后导航到一个'javascript:'url。工作,但不是很好。你知道'Document.parentWindow.ExecScript'是否阻塞吗?或者可能我的脚本在结果设置之前没有完成执行? (也会在一秒钟内测试自己)。我仍然想知道是否有一种方法可以纯粹用VB来完成它! – NickSlash 2013-03-03 23:49:53
这并不是说querySelector不能与IE9 + dll一起工作,我只是没有测试过那些 – mkingston 2013-03-03 23:50:44
@NickSlash我编辑了我的答案以回应您的评论。至于阻挡,我认为是这样,但我不确定。应该很容易测试(嵌套循环计数到2^31或JS中的最大整数)。 – mkingston 2013-03-04 00:02:05