python爬虫之爬取天气预报

在这篇博文,我们练习了利用beautifulsoup爬取了中国天气预报(http://www.weather.com.cn/textFC/gat.shtml),让我们一起学习一下吧~

python爬虫之爬取中国天气预报

  • 1.爬取步骤
  • 2.获取网页源代码
  • 3. 分析天气爬取规律
  • 4 保存文件
  • 5 完整爬取中国天气预报

1.爬取步骤

1.确认需求和目标url
2.获取网页源代码 (第一页为尝试)
3.分析网页爬取规律 (第一页为尝试,关键)
4.保存到csv文件

'''
需求:
1.爬取全国所有的城市名称以及对应的气温
2.保存所有的城市名称以及对应的气温到为csv文件

目标url:
1.华北地区: http://www.weather.com.cn/textFC/hb.shtml
2.东北地区:http://www.weather.com.cn/textFC/db.shtml
3.华东地区:http://www.weather.com.cn/textFC/hd.shtml
4.华中地区:http://www.weather.com.cn/textFC/hz.shtml
5.华南地区:http://www.weather.com.cn/textFC/hn.shtml
6.西北地区:http://www.weather.com.cn/textFC/xb.shtml
7.西南地区:http://www.weather.com.cn/textFC/xn.shtml
8.港澳台地区:http://www.weather.com.cn/textFC/gat.shtml
规律: 'http://www.weather.com.cn/textFC/' + dq_name + '.shtml' 其中,dq_name = [hb,db,hd,hz,hn,xb,xn,gat]
'''

2.获取网页源代码

# 2.获取网页源代码 (第一页为尝试)
import requests
def get_source(url):
    response = requests.get(url)
    response.encoding = 'utf-8'
    return response.text
##  测试
if __name__ == '__main__':
    url = 'http://www.weather.com.cn/textFC/hb.shtml'
    source = get_source(url)
    print(source)

3. 分析天气爬取规律

(1)确认分析的顺序
python爬虫之爬取天气预报_第1张图片
(2)确认整体表格存放位置,即北京、天津、河北、山西、内蒙古所有信息存放的表格
python爬虫之爬取天气预报_第2张图片

(3)确认小表格存放的元素,即北京、天津、河北、山西、内蒙古各自存放的位置
python爬虫之爬取天气预报_第3张图片
python爬虫之爬取天气预报_第4张图片
python爬虫之爬取天气预报_第5张图片
由此,我们知道,每个地区的天气信息是分别存储在table内容
下面,我们继续分析每个地区的具体天气信息存放地址:
python爬虫之爬取天气预报_第6张图片
python爬虫之爬取天气预报_第7张图片
由此,我们就可以确认代码该如何写了

# 3.分析天气爬取规律 (第一页为尝试,关键)
from bs4 import BeautifulSoup
def get_info(source):
    # 解决网页乱码,添加'html5lib',而不是lxml
    soup = BeautifulSoup(source, 'html5lib')  # pip install html5lib
    # 1.进入整体表格
    conMidtab = soup.find('div', class_='conMidtab')
    # 2.进入子表格
    tables = conMidtab.find_all('table')
    # 3.进入每个子表格收集天气信息
    info = []
    for table in tables:
        # (1)过滤前两个(城市和时间)
        trs = table.find_all('tr')[2:]  # tr存储了每个城市的天气信息
        # enumerate 返回2个值第一个是下标 第二个下标所对应的元素
        # (2)进入每个城市(每一行),判断是否是省会
        for index,tr in enumerate(trs):
            tds = tr.find_all('td')  # td存储每个城市天气信息的每个具体项目
            # 城市名字判断:因为对于每个省份的第一行的第一列为省名,对应不了省会。爬取会出错,因而要判断修改
            city_td = tds[0] # 城市
            if index == 0:  #  index==0,代表的是第一个tr,第一个城市
                city_td = tds[1] # 省会
        # (3)获取每个城市的具体天气项目
            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]
            # print('城市:', city, '最高气温:', temp_high,'最低气温:',temp_low)
            item = city,temp_high,temp_low
            info.append(item)
        return info  # 存储在info内部

##  测试
if __name__ == '__main__':
    url = 'http://www.weather.com.cn/textFC/hb.shtml'
    source = get_source(url)
    info = get_info(source)
    print(info)

得到结果如下:
python爬虫之爬取天气预报_第8张图片

4 保存文件

# 4.保存到csv文件
import csv
def save_weather(info):
    with open('weatherinfo.csv','w',encoding='UTF-8',newline='') as f:
        filenames = ['city','temp_high','temp_low']
        writer = csv.DictWriter(f,fieldnames=filenames)
        writer.writeheader() # 写入表头
        for each_city in info:
            each_city = list(each_city)
            dict_info = dict(zip(filenames,each_city))
            writer.writerow(dict_info)


##  测试
if __name__ == '__main__':
    url = 'http://www.weather.com.cn/textFC/hb.shtml'
    source = get_source(url)
    info = get_info(source)
    save_weather(info)

5 完整爬取中国天气预报

# 5.整个函数
def main():
    info_list = []
    dq_names = ['hb', 'db', 'hd', 'hz', 'hn', 'xb', 'xn', 'gat']
    for dq_name in dq_names:
        url = 'http://www.weather.com.cn/textFC/' + dq_name + '.shtml'
        source = get_source(url)
        info = get_info(source)
        info_list += info
    save_weather(info_list)

if __name__ == '__main__':
    main()

你可能感兴趣的:(python)