Excel VBA IE自动化:如何获取嵌套双层Div中的Input元素
Hey there! Let's break down why your code is throwing that "Object does not support this property or method" error and how to fix it to access that input element properly.
Why Your Original Code Failed
The issue lies in this line:
Set HTMLtags = oHtml.querySelector(".program-filters").getElementsByTagName("div").getElementsByTagName("input")
When you call getElementsByTagName("div"), it returns an HTMLCollection (a group of elements), not a single element. Collections don’t have the getElementsByTagName method—only individual HTML elements do. You can’t chain these calls directly on the collection; you need to target a specific element within the collection first.
Solution 1: Use querySelector Directly (Simplest Approach)
Since you already know the jQuery selector $('.program-filters input'), you can use the equivalent native CSS selector directly with querySelector to grab the input in one step. This is cleaner and avoids chain-related errors:
Dim inputElement As Object ' Wait for the input element to load Do DoEvents Set inputElement = oHtml.querySelector(".program-filters input") Loop While inputElement Is Nothing ' Now interact with the input, e.g.: inputElement.Value = "Your Search Value"
Solution 2: Step-by-Step Element Traversal
If you prefer breaking it down for clarity, you need to access individual elements from each collection before moving to the next tag search:
Dim programFiltersDiv As Object Dim innerDiv As Object Dim inputElement As Object ' Wait for the parent .program-filters div to exist Do DoEvents Set programFiltersDiv = oHtml.querySelector(".program-filters") Loop While programFiltersDiv Is Nothing ' Get the inner div (use index 0 since it's the first/only div inside) Do DoEvents Set innerDiv = programFiltersDiv.getElementsByTagName("div")(0) Loop While innerDiv Is Nothing ' Finally, grab the input element inside that div Do DoEvents Set inputElement = innerDiv.getElementsByTagName("input")(0) Loop While inputElement Is Nothing ' Interact with the input inputElement.Value = "Your Search Value"
Bonus: Triggering Events (If Needed)
Since you referenced code about createEvent and dispatchEvent, once you have the input element, you might need to trigger events to make the page recognize your input. For example:
' Trigger focus event to activate the input Dim eventFocus As Object Set eventFocus = oHtml.createEvent("HTMLEvents") eventFocus.initEvent "focus", True, False inputElement.dispatchEvent eventFocus ' Trigger input event after setting the value Dim eventInput As Object Set eventInput = oHtml.createEvent("HTMLEvents") eventInput.initEvent "input", True, False inputElement.dispatchEvent eventInput ' Click the GO button to submit the search Dim goButton As Object Set goButton = oHtml.querySelector(".in-map-btn.btn.btn-primary.btn-go.btn-mobile-fixed") If Not goButton Is Nothing Then goButton.Click
内容的提问来源于stack exchange,提问作者TheRealPapa

