python爬取全国的天气预报
时间: 2024-02-21 10:56:01 浏览: 26
要爬取全国的天气预报,你可以使用Python的爬虫库来实现。以下是一个简单的示例代码,使用了requests和BeautifulSoup库:
```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/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
html = response.text
soup = BeautifulSoup(html, 'html.parser')
weather_div = soup.find(class_='t').find_all('li')
for item in weather_div:
date = item.find(class_='time').text.strip()
weather = item.find(class_='wea').text.strip()
temperature = item.find(class_='tem').text.strip()
print(f'{date}:{weather},温度:{temperature}')
# 示例:获取北京的天气预报
get_weather('101010100')
```
这段代码使用了requests库发送HTTP请求,获取天气预报页面的HTML内容。然后使用BeautifulSoup库解析HTML,提取出需要的天气信息。你可以根据需要修改代码中的城市代码来获取其他城市的天气预报。
需要注意的是,爬取网站的数据时,请遵守网站的使用规则和相关法律法规,不要对网站造成过大的访问压力。