给我一个爬取天气数据的Python程序
时间: 2024-03-18 10:44:44 浏览: 15
以下是一个简单的Python程序,可以爬取中国天气网的天气数据:
```python
import requests
from bs4 import BeautifulSoup
# 爬取天气数据的函数
def get_weather(city):
url = 'http://www.weather.com.cn/weather/{}.shtml'.format(city)
response = requests.get(url)
response.encoding = 'utf-8'
html = response.text
soup = BeautifulSoup(html, 'html.parser')
weather = soup.find(class_='wea').text.strip()
temp = soup.find(class_='tem').text.strip()
return '天气:{},温度:{}'.format(weather, temp)
# 测试程序
if __name__ == '__main__':
city = 'beijing'
print(get_weather(city))
```
在上面的程序中,我们使用了 `requests` 库来发送 HTTP 请求,并使用 `BeautifulSoup` 库来解析 HTML 文档。具体地,我们通过访问 `http://www.weather.com.cn/weather/{city}.shtml` 这个网址来获取城市 `{city}` 的天气数据,然后使用 BeautifulSoup 来提取出天气和温度信息。在上面的测试程序中,我们以北京为例进行了测试,你可以将 `city` 变量设置为你所在的城市,然后运行程序查看天气数据。