Python网络爬虫(2)--爬取深圳最近7天天气状况

今天,在Python网络爬虫(1)的基础上,我们继续研究网络爬虫,今天要爬取的是中国天气网深圳最近7天的天气。
网站信息如图:


Screenshot from 2018-01-14 23-31-06.png

查看源码部分:


Screenshot from 2018-01-14 23-34-51.png

一.根据URL获取全部的HTML文本信息

def get_html(url):
    """
    获取HTML文本
    :param url:
    :return:
    """
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except socket.timeout:
        return ""

二.用BeautifulSoup解析获取的HTML文本

从查看源码得知:
最近7天的天气信息都被包含在

    里面,所以我们通过BeautifulSoup的find()方法首先定位到我们所关注的信息部分,然后再对里面的信息进行逐层解析,具体操作如下,

    def parse_html(html):
        """
        解析获取的HTML文本
        :param html:
        :return:
        """
        soup = BeautifulSoup(html, 'html.parser')
        ul = soup.find('ul', {'class': 't clearfix'})
        lis = ul.find_all('li')
        weather_list = []
        for li in lis:
            date = li.h1.string  # 日期
            ps = li.find_all('p')
            desc = ps[0].string  # 多云
            t = ps[1]
            if t.span is not None:
                temp = t.i.string + '~' + t.span.string
            else:
                temp = t.i.string
            w = ps[2].span.attrs
            wind = w['title'] + ',' + ps[2].i.string  # 无持续风向
            weather_list.append([date, desc, temp, wind])
        return weather_list
    

    中国天气网上,到了晚上,没有了最高温度,会出现为空的情况,所以要多做一次判断处理:

            if t.span is not None:
                temp = t.i.string + '~' + t.span.string
            else:
                temp = t.i.string
    

    三.将解析后的内容按一定格式存到文件

    def save_to_file(w_list):
        """
        数据写到到文件
        :param w_list:
        :return:
        """
        with open('shenzhen.txt', 'w') as f:
            tplt = "{0:<10}\t{1:<8}\t{2:<8}\t{3:<16}"
            h = tplt.format('日期','\t天气状况', '温度变化', '风向风速')
            print('深圳最近7天天气状况'.center(50), file=f)
            print(h, file=f)
            print('-'*60, file=f)
            for w in w_list:           
                s = tplt.format(str(w[0]), str(w[1]), str(w[2]), str(w[3]),chr(12288))
                print(s, file=f)
        f.close()
    

    存到文件后的效果如下:

                        深圳最近7天天气状况                    
    日期              天气状况    温度变化        风向风速            
    ------------------------------------------------------------
    14日(今天)     晴              13℃          无持续风向,<3级       
    15日(明天)     晴转多云         14℃~23℃     无持续风向,<3级       
    16日(后天)     多云            15℃~21℃     无持续风向,<3级       
    17日(周三)     多云            16℃~22℃     无持续风向,<3级       
    18日(周四)     多云转阴         15℃~21℃    无持续风向,<3级       
    19日(周五)     阴              14℃~19℃    无持续风向,<3级       
    20日(周六)     阴              14℃~18℃    无持续风向,<3级           
    

    你可能感兴趣的:(Python网络爬虫(2)--爬取深圳最近7天天气状况)