给我一个爬取石家庄市天气数据的案例
时间: 2024-04-21 20:24:04 浏览: 24
当然可以!这是一个爬取石家庄市天气数据的案例:
```python
import requests
from bs4 import BeautifulSoup
def get_weather(city):
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/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 = '101090101' # 石家庄市的城市代码是101090101
result = get_weather(city)
print(result)
```
这个案例使用了requests库和BeautifulSoup库来获取天气数据。在这个案例中,我们直接使用了石家庄市的城市代码进行查询天气数据。
注意:请确保安装了requests和beautifulsoup4库,可以使用`pip install requests beautifulsoup4`命令进行安装。另外,根据需要可能需要调整headers中的User-Agent参数。
希望这个案例能对你有所帮助!如果有任何问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)