如何在VBA中检测元素不存在?网页爬取判断代码失效求助
Fixing the VBA Check for "alert-block" Elements
Let me break down why your original code isn't working and how to fix it:
The Problem with Your Current Condition
When you use getElementsByClassName("alert-block"), it always returns an HTMLCollection object—even if there are no elements matching that class. It never returns Nothing, so your Is Nothing check will always evaluate to False, causing your code to always run the "任务2" block regardless of whether the element exists.
The Correct Way to Check
Instead of checking if the collection is Nothing, you need to check if its Length property is 0 (meaning no elements were found). Here's the revised code:
Dim alertBlocks As HTMLCollection Set alertBlocks = appIE.document.getElementsByClassName("alert-block") If alertBlocks.Length = 0 Then ' 执行任务1:获取正常数据 Dim projectStatus As String Dim numBids As String ' Optional: Add checks for these elements to avoid errors if they're missing too Dim statusElement As Object Dim bidsElement As Object Set statusElement = appIE.document.getElementById("project_status") Set bidsElement = appIE.document.getElementById("num-bids") If Not statusElement Is Nothing And Not bidsElement Is Nothing Then projectStatus = statusElement.innerText numBids = bidsElement.innerText ' Add your data processing code here Else MsgBox "One or more required elements are missing from the page!" End If Else ' 执行任务2:处理出现alert-block的情况 MsgBox "Page content has been modified - alert-block element detected!" ' Add your custom handling code here (e.g., log the issue, skip this page, etc.) End If
Key Notes:
- Storing the HTMLCollection in a variable (
alertBlocks) makes your code cleaner and avoids redundant calls to the DOM. - Adding checks for
getElementByIdresults (likestatusElementandbidsElement) makes your code more robust—if the page structure changes further, you'll get a clear warning instead of a runtime error. - The
Lengthproperty is the reliable way to check if a collection returned bygetElementsByClassNameorgetElementsByTagNamecontains any elements.
内容的提问来源于stack exchange,提问作者Hoang Manh Ha
相关产品推荐
相关产品推荐

