爬取重庆近半个月天气python代码
时间: 2023-10-10 07:08:37 浏览: 66
对于爬取重庆近半个月天气的Python代码,可以使用requests库来进行网络请求,然后解析返回的HTML页面获取所需的天气数据。以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_weather(city):
url = f'http://www.weather.com.cn/weather15d/{city}.shtml'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
weather_data = soup.find(class_='t clearfix').find_all('li')
weather_info = []
for item in weather_data:
date = item.find(class_='date').text
weather = item.find(class_='wea').text
temperature = item.find(class_='tem').text
weather_info.append({'date': date, 'weather': weather, 'temperature': temperature})
return weather_info
city = '重庆'
weather_info = get_weather(city)
for info in weather_info:
print(f"日期:{info['date']},天气:{info['weather']},温度:{info['temperature']}")
```