zoukankan      html  css  js  c++  java
  • 初识python 之 爬虫:爬取中国天气网数据

    用到模块:

    获取网页并解析:
    import requests,html5lib
    from bs4 import BeautifulSoup

    使用pyecharts的Bar可视化工具“绘制图表”,写入HTML文件,附pyecharts官方中文API地址:https://pyecharts.org/#/
    from pyecharts.charts import Bar

    表格主题设置:
    from pyecharts import options
    from pyecharts.globals import ThemeType

    获取时间
    from datetime import datetime

    详细代码如下:  注:代码中有使用到map函数,需要留意!

      1 #!/user/bin env python
      2 # author:Simple-Sir
      3 # time:2019/7/25 21:16
      4 # 爬取中国天气网数据
      5 
      6 import requests,html5lib
      7 from bs4 import BeautifulSoup
      8 from pyecharts.charts import Bar  # 官方已取消 pyecharts.Bar 方式导入
      9 from pyecharts import options
     10 from pyecharts.globals import ThemeType
     11 from datetime import datetime
     12 
     13 WEARTHER_DATE =[]  # 城市天气数据列表
     14 
     15 def urlText(url):
     16     '''
     17     获取网页HTML代码,并解析成文本格式
     18     :param url: 网页url地址
     19     :return: 解析之后的html文本
     20     '''
     21     headers = {
     22         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
     23     }
     24     respons = requests.get(url, headers=headers)  # 获取网页信息
     25     text = respons.content.decode('utf-8')  # 解析网页
     26     return text
     27 
     28 def getDiv(url,area):
     29     '''
     30     获取需要的html标签:城市、最高温度
     31     :param url:
     32     :param area: 区域:全国、全省(四川)  0:全国、其他任意值:全市
     33     :return:
     34     '''
     35     text = urlText(url)
     36     # soup = BeautifulSoup(text,'lxml') # 港澳台html中table标签解析错误
     37     soup = BeautifulSoup(text, 'html5lib')  # html5lib 容错性比lxml高
     38     conMidtab = soup.find_all('div',class_="conMidtab")[1]  # 获取“明天”的天气
     39     if area == '四川':
     40         # 获取四川所有城市天气
     41         trs = conMidtab.find_all('tr')[2:]
     42         for tr in trs:
     43             tds = tr.find_all('td')
     44             city_td = tds[0]
     45             city = list(city_td.stripped_strings)[0]  # 区县
     46             temp_td = tds[-5]  # 倒数第5个td标签
     47             temp = list(temp_td.stripped_strings)[0]  # 最高温度
     48             print('正在获取 {} 的最高气温:{}'.format(city, temp))
     49             WEARTHER_DATE.append({'城市': city, '最高温度': int(temp)})
     50     else:
     51         # 获取全国城市天气
     52         tables = conMidtab.find_all('table')
     53         for t in tables:
     54             trs = t.find_all('tr')[2:]
     55             for index, tr in enumerate(trs):
     56                 tds = tr.find_all('td')
     57                 if index == 0:
     58                     city_td = tds[1]  # city_td = tds[-8]  # 港澳台格式错误
     59                 else:
     60                     city_td = tds[0]
     61                 city = list(city_td.stripped_strings)[0]  # 区县
     62                 temp_td = tds[-5]  # 倒数第5个td标签
     63                 temp = list(temp_td.stripped_strings)[0]  # 最高温度
     64                 print('正在获取 {} 的最高气温:{}'.format(city,temp))
     65                 WEARTHER_DATE.append({'城市': city, '最高温度': int(temp)})
     66 
     67 
     68 # 可视化数据,对城市温度排名
     69 # def getRownum(data):
     70 #     max_temp = data['最高温度']  # 把列表里的每一项当作参数传进来,再获取“最高温度”这一项的值
     71 #     return max_temp
     72 # WEARTHER_DATE.sort(key=getRownum)  # 功能和它一样:WEARTHER_DATE.sort(key=lambda data:data['最高温度'])
     73 
     74 def main():
     75     city_list =['hb','db','hd','hz','hn','xb','xn','gat','sichuan']
     76     getcity = input('您要获取“全国”还是“四川”的最高温度排名?
    ')
     77     if getcity=='四川':
     78             url = 'http://www.weather.com.cn/textFC/{}.shtml'.format(city_list[-1])
     79             getDiv(url,getcity)
     80     else:
     81         for cl in city_list[:-1]:
     82             url = 'http://www.weather.com.cn/textFC/{}.shtml'.format(cl)
     83             getDiv(url,getcity)
     84     print('正在对天气温度进行排序处理...')
     85     WEARTHER_DATE.sort(key=lambda data: int(data['最高温度']))  # 对列表中的字典数据排序,温度从低到高
     86     WEARTHER_DATE.reverse()  # 把对列表反转,温度从高到低
     87     rownum = WEARTHER_DATE[:10]  # 获取最高温度排名前十的城市
     88     print('正在绘制图表...')
     89     # 分别获取城市、温度列表
     90     # 原始方法:
     91     # citys=[]
     92     # temps=[]
     93     # for i in rownum:
     94     #     citys.append(i['城市'])
     95     #     temps.append(i['最高温度'])
     96 
     97     # 高端方法:
     98     citys = list(map(lambda x: x['城市'], rownum))  # 使用map分离出城市
     99     temps = list(map(lambda x: x['最高温度'], rownum))  # 使用map分离出最高温度
    100     # 通过使用pyecharts的Bar可视化数据,附官方中文API地址:https://pyecharts.org/#/
    101     bar = Bar(init_opts = options.InitOpts(theme=ThemeType.DARK))  # 对表格添加主题
    102     bar.add_xaxis(citys)
    103     bar.add_yaxis('',temps)
    104     tim = datetime.now().strftime('%Y-%m-%d')
    105     bar.set_global_opts(title_opts={'text':'中国天气网 {} 城市明日最高温度排名前十({})'.format(getcity,tim)})
    106     bar.render('中国天气网城市最高温度排名.html')
    107     print('图表绘制已完成,结果已写入文件,请查看。')
    108 if __name__ == '__main__':
    109     main()
    爬取中国天气网数据

    执行过程:

    执行结果:

    四川:

    全国:

    世风之狡诈多端,到底忠厚人颠扑不破; 末俗以繁华相尚,终觉冷淡处趣味弥长。
  • 相关阅读:
    线程学习笔记(一)
    进程间通信
    管道通信操作
    在程序中执行shell命令
    进程控制(一)
    Makefile文件学习总结
    进程学习笔记
    C#不安全代码和指针
    Unity3D ShaderLab 修改渲染队列进行深度排序
    Unity3D ShaderLab 透明裁剪着色器
  • 原文地址:https://www.cnblogs.com/simple-li/p/11251703.html
Copyright © 2011-2022 走看看