最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python爬取天氣數(shù)據(jù)的實例詳解

 更新時間:2020年11月20日 14:43:35   作者:小妮淺淺  
在本篇文章里小編給大家整理的是一篇關(guān)于python爬取天氣數(shù)據(jù)的實例詳解內(nèi)容,有興趣的朋友們學(xué)習(xí)下。

就在前幾天還是二十多度的舒適溫度,今天一下子就變成了個位數(shù),小編已經(jīng)感受到冬天寒風(fēng)的無情了。之前對獲取天氣都是數(shù)據(jù)上的搜集,做成了一個數(shù)據(jù)表后,對溫度變化的感知并不直觀。那么,我們能不能用python中的方法做一個天氣數(shù)據(jù)分析的圖形,幫助我們更直接的看出天氣變化呢?

使用pygal繪圖,使用該模塊前需先安裝pip install pygal,然后導(dǎo)入import pygal

bar = pygal.Line() # 創(chuàng)建折線圖
bar.add('最低氣溫', lows)  #添加兩線的數(shù)據(jù)序列
bar.add('最高氣溫', highs) #注意lows和highs是int型的列表
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
bar.x_label_rotation = 45
bar.title = cityname+'未來七天氣溫走向圖'  #設(shè)置圖形標(biāo)題
bar.x_title = '日期'  #x軸標(biāo)題
bar.y_title = '氣溫(攝氏度)' # y軸標(biāo)題
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
bar.render_to_file('temperate1.svg') # 將圖像保存為SVG文件,可通過瀏覽器

最終生成的圖形如下圖所示,直觀的顯示了天氣情況:

完整代碼

import csv
import sys
import urllib.request
from bs4 import BeautifulSoup # 解析頁面模塊
import pygal
import cityinfo
 
cityname = input("請輸入你想要查詢天氣的城市:")
if cityname in cityinfo.city:
  citycode = cityinfo.city[cityname]
else:
  sys.exit()
url = '非常抱歉,網(wǎng)頁無法訪問' + citycode + '.shtml'
header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36") # 設(shè)置頭部信息
http_handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(http_handler) # 修改頭部信息
opener.addheaders = [header]
request = urllib.request.Request(url) # 制作請求
response = opener.open(request) # 得到應(yīng)答包
html = response.read() # 讀取應(yīng)答包
html = html.decode('utf-8') # 設(shè)置編碼,否則會亂碼
# 根據(jù)得到的頁面信息進行初步篩選過濾
final = [] # 初始化一個列表保存數(shù)據(jù)
bs = BeautifulSoup(html, "html.parser") # 創(chuàng)建BeautifulSoup對象
body = bs.body
data = body.find('div', {'id': '7d'})
print(type(data))
ul = data.find('ul')
li = ul.find_all('li')
# 爬取自己需要的數(shù)據(jù)
i = 0 # 控制爬取的天數(shù)
lows = [] # 保存低溫
highs = [] # 保存高溫
daytimes = [] # 保存日期
weathers = [] # 保存天氣
for day in li: # 便利找到的每一個li
  if i < 7:
    temp = [] # 臨時存放每天的數(shù)據(jù)
    date = day.find('h1').string # 得到日期
    #print(date)
    temp.append(date)
    daytimes.append(date)
    inf = day.find_all('p') # 遍歷li下面的p標(biāo)簽 有多個p需要使用find_all 而不是find
    #print(inf[0].string) # 提取第一個p標(biāo)簽的值,即天氣
    temp.append(inf[0].string)
    weathers.append(inf[0].string)
    temlow = inf[1].find('i').string # 最低氣溫
    if inf[1].find('span') is None: # 天氣預(yù)報可能沒有最高氣溫
      temhigh = None
      temperate = temlow
    else:
      temhigh = inf[1].find('span').string # 最高氣溫
      temhigh = temhigh.replace('℃', '')
      temperate = temhigh + '/' + temlow
    # temp.append(temhigh)
    # temp.append(temlow)
    lowStr = ""
    lowStr = lowStr.join(temlow.string)
    lows.append(int(lowStr[:-1])) # 以上三行將低溫NavigableString轉(zhuǎn)成int類型并存入低溫列表
    if temhigh is None:
      highs.append(int(lowStr[:-1]))
      highStr = ""
      highStr = highStr.join(temhigh)
      highs.append(int(highStr)) # 以上三行將高溫NavigableString轉(zhuǎn)成int類型并存入高溫列表
    temp.append(temperate)
    final.append(temp)
    i = i + 1
# 將最終的獲取的天氣寫入csv文件
with open('weather.csv', 'a', errors='ignore', newline='') as f:
  f_csv = csv.writer(f)
  f_csv.writerows([cityname])
  f_csv.writerows(final)
# 繪圖
bar = pygal.Line() # 創(chuàng)建折線圖
bar.add('最低氣溫', lows)
bar.add('最高氣溫', highs)
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
# bar.show_minor_x_labels = False # 不顯示X軸最小刻度
bar.x_label_rotation = 45
bar.title = cityname+'未來七天氣溫走向圖'
bar.x_title = '日期'
bar.y_title = '氣溫(攝氏度)'
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
bar.render_to_file('temperate.svg')

Python爬取天氣數(shù)據(jù)實例擴展:

import requests
from bs4 import BeautifulSoup
from pyecharts import Bar

ALL_DATA = []
def send_parse_urls(start_urls):
  headers = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
  }
  for start_url in start_urls:
    response = requests.get(start_url,headers=headers)
    # 編碼問題的解決
    response = response.text.encode("raw_unicode_escape").decode("utf-8")
    soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能比較好,html5lib:適合頁面結(jié)構(gòu)比較混亂的
    div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一個元素
    tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表
    for table in tables:
      trs = table.find_all("tr")
      info_trs = trs[2:]
      for index,info_tr in enumerate(info_trs): # 枚舉函數(shù),可以獲得索引
        # print(index,info_tr)
        # print("="*30)
        city_td = info_tr.find_all("td")[0]
        temp_td = info_tr.find_all("td")[6]
        # if的判斷的index的特殊情況應(yīng)該在一般情況的后面,把之前的數(shù)據(jù)覆蓋
        if index==0:
          city_td = info_tr.find_all("td")[1]
          temp_td = info_tr.find_all("td")[7]
        city=list(city_td.stripped_strings)[0]
        temp=list(temp_td.stripped_strings)[0]
        ALL_DATA.append({"city":city,"temp":temp})
  return ALL_DATA

def get_start_urls():
  start_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",
    "http://www.weather.com.cn/textFC/gat.shtml",
  ]
  return start_urls

def main():
  """
  主程序邏輯
  展示全國實時溫度最低的十個城市氣溫排行榜的柱狀圖
  """
  # 1 獲取所有起始url
  start_urls = get_start_urls()
  # 2 發(fā)送請求獲取響應(yīng)、解析頁面
  data = send_parse_urls(start_urls)
  # print(data)
  # 4 數(shù)據(jù)可視化
    #1排序
  data.sort(key=lambda data:int(data["temp"]))
    #2切片,選擇出溫度最低的十個城市和溫度值
  show_data = data[:10]
    #3分出城市和溫度
  city = list(map(lambda data:data["city"],show_data))
  temp = list(map(lambda data:int(data["temp"]),show_data))
    #4創(chuàng)建柱狀圖、生成目標(biāo)圖
  chart = Bar("中國最低氣溫排行榜") #需要安裝pyechart模塊
  chart.add("",city,temp)
  chart.render("tempture.html")

if __name__ == '__main__':
  main()

到此這篇關(guān)于python爬取天氣數(shù)據(jù)的實例詳解的文章就介紹到這了,更多相關(guān)python爬蟲天氣數(shù)據(jù)的分析內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python3之亂碼\xe6\x97\xa0\xe6\xb3\x95處理方式

    Python3之亂碼\xe6\x97\xa0\xe6\xb3\x95處理方式

    這篇文章主要介紹了Python3之亂碼\xe6\x97\xa0\xe6\xb3\x95處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • 基于Python實現(xiàn)多圖繪制系統(tǒng)

    基于Python實現(xiàn)多圖繪制系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了如何基于Python實現(xiàn)一個簡單的多圖繪制系統(tǒng),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-02-02
  • pycharm from lxml import etree標(biāo)紅問題及解決

    pycharm from lxml import etree標(biāo)紅問題及解決

    這篇文章主要介紹了pycharm from lxml import etree標(biāo)紅問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • 使用Python繪制空氣質(zhì)量日歷圖

    使用Python繪制空氣質(zhì)量日歷圖

    這篇文章主要介紹了使用Python繪制空氣質(zhì)量日歷圖,文章基于Python繪制的相關(guān)知識展開對空氣質(zhì)量日歷圖的繪制,感興趣的小伙伴可以參考一下
    2022-05-05
  • Python continue繼續(xù)循環(huán)用法總結(jié)

    Python continue繼續(xù)循環(huán)用法總結(jié)

    本篇文章給大家總結(jié)了關(guān)于Python continue繼續(xù)循環(huán)的相關(guān)知識點以及用法,有需要的朋友跟著學(xué)習(xí)下吧。
    2018-06-06
  • Python在報表自動化的優(yōu)勢及實現(xiàn)流程

    Python在報表自動化的優(yōu)勢及實現(xiàn)流程

    本文利用Python實現(xiàn)報表自動化,通過介紹環(huán)境設(shè)置、數(shù)據(jù)收集和準(zhǔn)備、報表生成以及自動化流程,展示Python的靈活性和豐富的生態(tài)系統(tǒng)在報表自動化中的卓越表現(xiàn),從設(shè)置虛擬環(huán)境到使用Pandas和Matplotlib處理數(shù)據(jù),到借助APScheduler實現(xiàn)定期自動化,每個步驟都得到詳盡闡述
    2023-12-12
  • Python實現(xiàn)一個優(yōu)先級隊列的方法

    Python實現(xiàn)一個優(yōu)先級隊列的方法

    這篇文章主要介紹了Python實現(xiàn)一個優(yōu)先級隊列的方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 最新評論

    茌平县| 新泰市| 汝州市| 乐安县| 皋兰县| 右玉县| 广平县| 红河县| 台南市| 神农架林区| 南昌县| 大田县| 阿拉善盟| 基隆市| 洛阳市| 东丰县| 刚察县| 楚雄市| 沭阳县| 当阳市| 延长县| 东源县| 静宁县| 江都市| 岗巴县| 北宁市| 化州市| 盐源县| 隆子县| 威宁| 搜索| 安吉县| 绩溪县| 尼玛县| 晋宁县| 梧州市| 团风县| 诸暨市| 河东区| 林周县| 江达县|