天气信息对于很多应用来说都是非常重要的数据,无论是旅行计划还是决策制定,都需要准确的天气预报。在本篇文章中,我们将介绍如何使用Python编写一个简单的爬虫,从中国天气网获取天气信息,并将这些数据保存到CSV文件中。
准备工作
在开始之前,确保您已经安装了以下Python库:
requests
:用于发送HTTP请求。BeautifulSoup
:用于解析HTML页面。pandas
:用于处理和保存数据。
您可以使用以下命令来安装这些库:
python
pip install requests beautifulsoup4 pandas
代码实现
下面是我们的Python代码,它将从中国天气网抓取天气信息并将其保存到CSV文件中:
import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd
def get_source(url):
response = requests.get(url)
response.encoding = 'utf-8'
return response.text
def get_info(source):
soup = BeautifulSoup(source, 'html.parser')
conMidtab = soup.find('div', class_='conMidtab')
tables = conMidtab.find_all('table')
info = []
for table in tables:
trs = table.find_all('tr')[2:]
for index, tr in enumerate(trs):
tds = tr.find_all('td')
city_td = tds[0]
if index == 0:
city_td = tds[1]
city = list(city_td.stripped_strings)[0]
temp_high_td = tds[-5]
temp_high = list(temp_high_td.stripped_strings)[0]
temp_low_td = tds[-2]
temp_low = list(temp_low_td.stripped_strings)[0]
item = ('城市',city,'最高温度', temp_high,'最低温度', temp_low)
info.append([city, temp_high, temp_low])
df = pd.DataFrame(info, columns=['城市', '最高温度', '最低温度'])
df.to_csv('天气预报.csv', index=False, encoding='utf-8')
return info
if __name__ == '__main__':
url = 'http://www.weather.com.cn/textFC/hb.shtml'
source = get_source(url)
info = get_info(source)
print(info)
代码解释
- 我们使用
requests
库向中国天气网发送HTTP请求,获取网页源代码。 - 然后,我们使用
BeautifulSoup
库解析HTML页面,提取我们需要的数据,这里是各个城市的最高温度和最低温度。 - 最后,我们使用
pandas
库将数据保存到CSV文件中,以便后续分析和使用。
最后效果
结语
在这篇文章中,我们介绍了如何使用Python编写一个简单的爬虫,从中国天气网获取天气信息并保存到CSV文件中。这只是一个简单的示例,您可以根据自己的需求进一步扩展和定制这个爬虫。希望这篇文章能对你有所帮助!