python天气代码
时间: 2023-12-21 20:31:45 浏览: 33
以下是一个使用Python获取天气信息的示例代码:
```python
import requests
def get_weather(city):
result = requests.get(f'https://www.weather.com.cn/data/sk/{city}.html')
result.encoding = 'utf-8'
weather_info = result.json()
print(weather_info)
get_weather('101010100') # 北京
```
这段代码使用了`requests`库发送HTTP请求,获取天气信息。通过调用`get_weather`函数并传入城市代码(例如`101010100`代表北京),可以获取该城市的天气信息。代码中的`print(weather_info)`语句将天气信息打印出来。
相关问题
python天气爬虫代码
以下是一个简单的Python天气爬虫代码,可以获取指定城市的天气情况:
```python
import requests
from bs4 import BeautifulSoup
city = input("请输入城市名:")
url = f"http://www.weather.com.cn/weather/{city}.shtml"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = soup.select(".t .clearfix")
for weather in weather_list:
date = weather.select(".week")[0].text
weather_desc = weather.select(".wea")[0].text
temperature = weather.select(".tem")[0].text
print(date, weather_desc, temperature)
```
使用时只需要输入指定城市,即可输出该城市未来七天的天气情况。需要注意的是,该代码依赖于requests和BeautifulSoup库,请确保这两个库已经安装。
python 获取天气代码
您好!以下是使用Python获取天气代码的示例:
```python
import requests
# 用于查询的城市名,这里以北京为例
city = 'beijing'
# 天气 API 的地址
url = f'http://wthrcdn.etouch.cn/weather_mini?city={city}'
# 发送请求获取天气数据
response = requests.get(url)
# 将返回的 JSON 数据转换为 Python 对象
weather_data = response.json()
# 打印天气信息
print(f'城市:{weather_data["data"]["city"]}')
print(f'温度:{weather_data["data"]["wendu"]}℃')
print(f'风向:{weather_data["data"]["forecast"][0]["fengxiang"]}')
print(f'天气:{weather_data["data"]["forecast"][0]["type"]}')
```
以上代码中,我们使用了 `requests` 库向天气 API 发送请求,获取返回的 JSON 数据,然后将数据转换为 Python 对象,最后输出相关的天气信息。请注意,此代码仅供参考,具体实现方式可能因 API 的不同而有所差异。