獲取中國(guó)天氣網(wǎng)最低溫度數(shù)據(jù)

1.需要提前安裝的庫(kù)

  1. bs4 (BeautifulSoup) : 解析網(wǎng)頁(yè)
  2. requests:網(wǎng)絡(luò)請(qǐng)求
  3. pyecharts : 數(shù)據(jù)可視化

2.環(huán)境

Python3.6.3

4.全部代碼

# /usr/bin/env python2.7
# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup
import requests
import time
import json

from pyecharts import Bar

TEMPERATURE_LIST = []

def getWether(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
        'Referer': 'http://www.weather.com.cn/forecast/',
        'Host': 'www.weather.com.cn',
        'Upgrade-Insecure-Requests': '1'
    }

    req = requests.get(url, headers=headers)

    content = req.content.decode('utf-8')

    soup = BeautifulSoup(content, 'lxml')

    conMid = soup.find('div', class_='conMidtab')

    conMidtab2_list = conMid.find_all('div', class_='conMidtab2')

    for x in conMidtab2_list:

        tr_list = x.find_all('tr')[2:]  # 排除 前面兩個(gè) 標(biāo)題行tr
        province = ''
        for index, tr in enumerate(tr_list):

            if index == 0:
                td_list = tr.find_all('td')
                province = td_list[0].text.replace('\n', '')
                city = td_list[1].text.replace('\n', '')
                min = td_list[7].text.replace('\n', '')
            else:
                td_list = tr.find_all('td')
                city = td_list[0].text.replace('\n', '')
                min = td_list[6].text.replace('\n', '')

            # print(province + city + min)

            TEMPERATURE_LIST.append({
                'city':city,
                'min':min
            })



def writeFile():
    urls = ['http://www.weather.com.cn/textFC/hb.shtml',
            'http://www.weather.com.cn/textFC/db.shtml',
            'http://www.weather.com.cn/textFC/hd.shtml',
            'http://www.weather.com.cn/textFC/hz.shtml',
            'http://www.weather.com.cn/textFC/hn.shtml',
            'http://www.weather.com.cn/textFC/xb.shtml',
            'http://www.weather.com.cn/textFC/xn.shtml']

    for url in urls:
        getWether(url)
        time.sleep(3)

    tem = json.dumps(TEMPERATURE_LIST,ensure_ascii=False)
    with open('temperature.json','w') as fr:
        fr.write(tem)


def openFile():
    print('制作柱狀圖')

    with open('temperature.json','r') as fr:
        TEMPERATURE_LIST = json.load(fr,encoding='utf-8')


    TEMPERATURE_LIST.sort(key=lambda x:(int(x['min']),int(x['min'])))

    TOP20_TEMPERATURE_LIST = TEMPERATURE_LIST[:20]
    CITY_LIST = []
    MINTEMPERATURE_LIST = []

    for dict1 in TOP20_TEMPERATURE_LIST:
        CITY_LIST.append(dict1['city'])
        MINTEMPERATURE_LIST.append(dict1['min'])


    bar = Bar(u'全國(guó)最低溫度前20排行榜',u'XXX貢獻(xiàn)')
    bar.add(u'最低溫度排行',CITY_LIST,MINTEMPERATURE_LIST,is_more_utils=True)

    bar.show_config()
    bar.render()


def main():
    # writeFile()   #先獲取數(shù)據(jù),保存到本地
    openFile()     #獲取完成后,直接取本地的數(shù)據(jù)


if __name__ == '__main__':
    main()

4.最后完成的效果截圖

data.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容