You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python minidom解析多站点XHTML获取天气预报的问题

How to Parse Weather Forecasts with Python minidom (Without Relying Solely on Tag Names)

Got it, let's solve this problem. The issue with just using getElementsByTagName("h4") is that different weather sites will have varying numbers of <h4> tags, so we can't guarantee we'll grab the right one. Instead, we should target elements by their class attributes alongside their tag names—this is way more reliable since weather components almost always have unique class identifiers tied to them.

Here's a step-by-step solution using minidom:

Step 1: Create a Helper Function to Filter Elements by Tag + Class

Minidom doesn't have a built-in method to search by class, so we'll make a simple function to do that for us:

from xml.dom.minidom import parseString

def get_element_by_tag_and_class(doc, tag_name, target_class):
    # Grab all elements with the specified tag
    all_elements = doc.getElementsByTagName(tag_name)
    # Loop through and find the one with the matching class
    for elem in all_elements:
        if elem.getAttribute("class") == target_class:
            return elem
    # Return None if no match is found
    return None

Step 2: Parse Your XHTML and Extract Weather Data

Now we can use this function to pull out the exact weather components we need from your XHTML snippet:

# Your target XHTML content
xhtml_snippet = """
<div class="pull-left" id="current-temps-cont"> 
  <h4 class="myforecast-current">Cloudy</h4> 
  <h1 class="myforecast-current-lrg">57&#176;F</h1> 
  <h3 class="myforecast-current-sm">14&#176;C</h3> 
</div>
"""

# Parse the XHTML string into a minidom document
doc = parseString(xhtml_snippet)

# Extract each weather component using our helper function
weather_condition = get_element_by_tag_and_class(doc, "h4", "myforecast-current")
temp_fahrenheit = get_element_by_tag_and_class(doc, "h1", "myforecast-current-lrg")
temp_celsius = get_element_by_tag_and_class(doc, "h3", "myforecast-current-sm")

# Print out the results (with checks to avoid errors if elements are missing)
if weather_condition:
    print(f"Current Condition: {weather_condition.firstChild.nodeValue.strip()}")
if temp_fahrenheit:
    print(f"Temperature (F): {temp_fahrenheit.firstChild.nodeValue.strip()}")
if temp_celsius:
    print(f"Temperature (C): {temp_celsius.firstChild.nodeValue.strip()}")

How This Works

  • The helper function first fetches all elements of a given tag (like <h4>), then filters them to find the one with the exact class we're targeting (e.g., myforecast-current).
  • This approach is robust across different weather sites because you just need to identify the unique class names tied to each weather component (you can find these using your browser's dev tools) instead of counting tag positions.

Note

If you're dealing with non-standard HTML (not strict XHTML), minidom might throw errors. In that case, you might want to pre-process the HTML with a library like html5lib to convert it to a valid DOM first—but for your provided XHTML snippet, this solution works perfectly.

内容的提问来源于stack exchange,提问作者VinAbb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:11:46