python爬取自己家乡10日内的天气预报
时间: 2023-08-17 08:05:37 浏览: 58
好的,这个问题可以使用 Python 中的 requests 和 BeautifulSoup 库来实现。首先需要找到一个提供天气预报信息的网站,例如中国天气网。
以下是一个简单的代码示例,可以爬取中国天气网上自己家乡10日内的天气预报:
```python
import requests
from bs4 import BeautifulSoup
# 设置城市名称和城市代码
city_name = "xxx" # 替换成你自己的城市名称
city_code = "xxx" # 替换成你自己的城市代码
# 构造请求URL
url = f"http://www.weather.com.cn/weather/{city_code}.shtml"
# 发送请求
response = requests.get(url)
# 解析HTML内容
soup = BeautifulSoup(response.content, "html.parser")
weather_items = soup.find_all("div", class_="t")
# 输出未来10天的天气预报
for item in weather_items:
date = item.find("h1").text
weather = item.find(class_="wea").text
temperature = item.find(class_="tem").text.strip()
print(f"{date},{weather},{temperature}")
```
需要注意的是,每个城市的代码不同,需要根据实际情况进行替换。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)