基于VBA抓取Accuweather班加罗尔当前天气的技术咨询
Fixing VBA Code to Scrape Current Temperature from Accuweather (Bengaluru)
Let's work through your problem step by step. Your goal is to grab the current temperature (the 88 value you referenced) from the Bengaluru Accuweather page, but your existing code has a few critical gaps:
- Wrong URL: You’re targeting the India homepage instead of the specific Bengaluru forecast page you need.
- Incomplete element selector: The
getElementsByClassName("panel...snippet is cut off, and even if finished, it likely targets the wrong element for the current temperature. - Missing anti-blocking safeguards: Accuweather often blocks requests from
XMLHTTP60by default because it doesn’t send a proper browser-like user agent header.
Here’s the revised, fully functional code that fixes all these issues:
Sub Get_Current_Temperature() Dim HTTP As New XMLHTTP60 Dim HTML As New HTMLDocument Dim tempElement As HTMLDivElement ' Use the exact Bengaluru forecast URL you specified Const targetURL As String = "https://www.accuweather.com/en/in/bengaluru/204108/weather-forecast/204108" With HTTP ' Add a user agent to mimic a real browser request (avoids being blocked) .Open "GET", targetURL, False .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" .send ' Load the response only if the request succeeded If .Status = 200 Then HTML.body.innerHTML = .responseText Else MsgBox "Failed to fetch data. Status code: " & .Status Exit Sub End If End With ' Target the current temperature element (verify selector via browser dev tools if it breaks later) Set tempElement = HTML.querySelector(".current-weather-info .temp") If Not tempElement Is Nothing Then ' Extract the numeric value by removing the degree symbol Dim currentTemp As String currentTemp = Replace(tempElement.innerText, "°", "") MsgBox "Current temperature in Bengaluru: " & currentTemp & "°" Else MsgBox "Temperature element not found. Check if the page structure has been updated." End If ' Clean up objects to free memory Set HTTP = Nothing Set HTML = Nothing Set tempElement = Nothing End Sub
Important Details:
- Required References: Enable these in the VBA editor (Tools > References) before running the code:
Microsoft XML, v6.0Microsoft HTML Object Library
- Element Selector: I used
.current-weather-info .tempwhich targets the current temperature display. If Accuweather updates their page layout later, right-click the temperature value in your browser, select "Inspect", and copy the new selector/class name to update the code. - User Agent: This header makes your request look like it’s coming from a regular web browser, drastically reducing the chance of being blocked.
- Error Handling: The code checks for a successful HTTP response and verifies the temperature element exists before attempting to extract data, preventing crashes from missing elements.
内容的提问来源于stack exchange,提问作者Ragu
相关产品推荐
相关产品推荐

