VBA数据从网站上刮去

document.getElementsByTagName(“tr”)。当我执行VBA脚本来查找特定网页上tr元素的数量时,length返回零

Sub AutomaticMode() Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True IE.Navigate "https://www.example.com/" Do While IE.readyState < 4 Application.StatusBar = "DOM Loading ..." Loop Set username_field = IE.document.getElementByID("username") username_field.Value = "username" Set password_field = IE.document.getElementByID("password") password_field.Value = "password" SendKeys "{Tab}{Enter}" Do While IE.readyState < 4 Application.StatusBar = "DOM Loading ..." Loop Dim trList As IHTMLElementCollection Set trList = IE.document.getElementsByTagName("tr") MsgBox (trList.Length) End Sub 

在页面完全加载之前,在您的网站上找不到tr标签可能会导致macros执行。 尝试改变:

 Do While IE.readyState < 4 

至:

 Do While IE.readyState < 4 or IE.Busy 

即使这并不能保证在发射macros之前所有的东西都会被加载,但是通常也是有帮助的,并且总是包含它的好习惯。 有时你需要find在前端显示“加载”等对象,并通过HTML元素循环,直到消失 – 然后你可以安全地运行你的脚本。