Python兰州十五天天气爬虫代码
时间: 2024-04-27 18:18:52 浏览: 124
当然,我可以为您介绍一下Python编写的兰州十五天天气爬虫代码。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_weather():
url = "http://www.weather.com.cn/weather/101160101.shtml"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537. (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36"
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = []
weather_divs = soup.find_all('div', class_='c7d')
for weather_div in weather_divs:
date = weather_div.find('h1').text.strip()
weather = weather_div.find('p', class_='wea').text.strip()
temperature = weather_div.find('p', class_='tem').text.strip().replace('\n', '')
weather_list.append((date, weather, temperature))
return weather_list
if __name__ == "__main__":
weather_data = get_weather()
for data in weather_data:
print(f"日期:{data},天气:{data},温度:{data}")
```
这段代码使用了`requests`库发送HTTP请求,使用`BeautifulSoup`库解析HTML页面。它通过访问中国天气网的兰州天气页面,获取了未来十五天的天气信息,并将日期、天气和温度存储在一个列表中。最后,通过遍历列表,将天气信息打印出来。
阅读全文