背景介绍
本项目旨在实现一个简单的网页应用,用户输入城市名称后可查看对应城市的天气情况。该网页无需依赖任何框架或外部服务,仅通过本地环境即可独立运行。实现过程中需要掌握网络请求和数据处理的核心知识,能够完成从HTML表单到JavaScript动态渲染的完整流程。
思路分析
- 前端构建
使用HTML、CSS和JavaScript构建界面,实现用户输入与天气信息展示的交互。通过input元素接收用户输入,结合JavaScript动态生成天气信息显示区域。 -
后端逻辑处理
在Python环境中,通过requests库发起HTTP请求获取天气数据。模拟API返回的JSON数据,解析并渲染结果到网页。 -
数据处理与渲染
将请求结果中的天气信息以HTML格式返回,用户输入城市名称后显示预设的天气描述。
代码实现
1. HTML表单与样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>城市天气</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
text-align: center;
}
input, select {
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
#weather {
width: 100%;
height: 200px;
background-color: #f4f4f4;
}
</style>
</head>
<body>
<h1>城市天气</h1>
<input type="text" id="cityInput" placeholder="输入城市名称..." required>
<div id="weather"></div>
<script>
const cityInput = document.getElementById('cityInput');
const weather = document.getElementById('weather');
cityInput.addEventListener('input', () => {
const city = cityInput.value.trim();
fetch(`https://api.example.com/weather?city=${city}`)
.then(response => response.json())
.then(data => {
weather.innerHTML = `<p>当前天气:${data.weather}</p>`;
})
.catch(error => {
weather.textContent = `无法获取天气信息,请稍后再试:${error.message}`;
});
});
</script>
</body>
</html>
2. Python实现代码
import requests
def get_weather(city):
"""获取城市天气信息"""
api_key = 'YOUR_API_KEY' # 替换为实际API密钥
url = f'http://api.example.com/weather?city={city}'
try:
response = requests.get(url, headers={'Authorization': api_key})
response.raise_for_status()
return response.json()
except exceptions.RequestException as e:
print(f"请求失败:{e}")
return None
# 示例输入
if __name__ == '__main__':
city = input("请输入城市名称:\n")
weather_data = get_weather(city)
if weather_data:
print(f"当前天气:{weather_data['weather']}") # 示例输出
else:
print("无法获取天气信息,请稍后再试!")
总结
本项目通过Python实现了一个独立运行的网页应用,用户只需输入城市名称即可查看天气信息。整个实现过程包括前端界面的构建、后端逻辑的处理,以及HTTP请求的封装。通过模拟实际天气API的响应,能够验证网络请求和数据处理的正确性。该实现不仅提升了对网络请求的理解,还积累了处理数据和动态渲染的经验。