29-爬取天气信息

借助中国气象局的API可以得到天气数据 :  https://www.jianshu.com/p/e3e04cf3fc0f?tdsourcetag=s_pctim_aiomsg

from bs4 import BeautifulSoup

def get_weather():
        url = 'http://flash.weather.com.cn/wmaps/xml/china.xml'
        html = requests.get(url).text.encode('iso-8859-1')#.decode('utf-8')
        bs = BeautifulSoup(html, 'lxml')
        list = bs.findAll('city')
        print('省份    城市         最高气温  最低气温  温度状态      最低风  最高风   风转态')
        print('-' * 90)
        #print('%-3s	%-4s	%-4s	%-4s	%-10s	%-4s	%-4s	%-10s' % ('省份', '城市', '最高气温', '最低气温', '温度>    状态', '最低风', '最高风', '风转态'))
        for tp in list:
                print('%-3s	%-6s	%-4s	%-4s	%-10s	%-4s	%-4s	%-10s' % ( tp['quname'], tp['cityname'],tp['state1'], tp['state2'], tp['statedetailed'], tp['tem1'], tp['tem2'], tp['windstate']))

        #print(list[0])
        print(len(list))

get_weather()

  效果如下(格式控制是可能在会出问题):

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/9870472.html