给我一个爬取天气数据的案例
时间: 2024-04-18 15:30:46 浏览: 11
当然可以!这里是一个简单的爬取天气数据的案例:
```python
import requests
from bs4 import BeautifulSoup
def get_weather(city):
url = f'https://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/88.0.4324.190 Safari/537.36'
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
html = response.text
soup = BeautifulSoup(html, 'html.parser')
weather_data = soup.find(class_='tem')
temperature = weather_data.span.string
weather_info = soup.find(class_='wea').string
return f'{city}的天气为:{weather_info},温度:{temperature}'
city = input('请输入城市名称:')
result = get_weather(city)
print(result)
```
这个案例使用了requests库和BeautifulSoup库来获取天气数据。用户需要输入城市名称,然后程序会从中国天气网爬取该城市的天气信息并返回显示。
注意:请确保安装了requests和beautifulsoup4库,可以使用`pip install requests beautifulsoup4`命令进行安装。另外,根据需要可能需要调整headers中的User-Agent参数。
希望这个案例能对你有所帮助!如果有任何问题,请随时提问。