python爬虫爬取一天内24小时天气
时间: 2023-07-23 22:14:09 浏览: 47
可以使用Python的requests库和BeautifulSoup库来实现爬取天气数据的功能。以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_weather():
# 发送GET请求获取网页内容
url = "https://www.weather.com"
response = requests.get(url)
content = response.content
# 解析网页内容
soup = BeautifulSoup(content, 'html.parser')
weather_data = soup.find_all(class_="hourly-forecast-card")
# 提取天气信息
weather_info = []
for data in weather_data:
time = data.find(class_="hourly-time").text
temperature = data.find(class_="temp").text
description = data.find(class_="phrase").text
weather_info.append((time, temperature, description))
return weather_info
# 调用函数获取天气信息
weather_info = get_weather()
# 打印天气信息
for info in weather_info:
print(f"时间:{info[0]},温度:{info[1]},描述:{info[2]}")
```
这段代码会从指定的网站上获取天气信息,并打印出每个小时的温度和描述。你可以根据需要修改代码中的网址和解析规则来适配不同的网站。