溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python如何讀取網(wǎng)絡數(shù)據(jù)

發(fā)布時間:2020-09-23 14:27:26 來源:億速云 閱讀:129 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)Python如何讀取網(wǎng)絡數(shù)據(jù),小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

很多時候,程序并不能直接展示本地文件中的數(shù)據(jù),此時需要程序讀取網(wǎng)絡數(shù)據(jù),并展示它們。

比如前面介紹的 http://lishi.tianqi.com 站點的數(shù)據(jù),它并未提供下載數(shù)據(jù)的鏈接(前面程序所展示的 csv 文件本身就是使用程序抓取下來的)。在這種情況下,程序完全可以直接解析網(wǎng)絡數(shù)據(jù),然后將數(shù)據(jù)展示出來。

前面已經(jīng)介紹了 Python 的網(wǎng)絡支持庫 urllib,通過該庫下的 request 模塊可以非常方便地向遠程發(fā)送 HTTP 請求,獲取服務器響應。因此,本程序的思路是使用 urllib.request 向 lishi.tianqi.com 發(fā)送請求,獲取該網(wǎng)站的響應,然后使用 Python 的 re 模塊來解析服務器響應,從中提取天氣數(shù)據(jù)。

本程序?qū)ㄟ^網(wǎng)絡讀取 http://lishi.tianqi.com 站點的數(shù)據(jù),并展示 2017 年廣州的最高氣溫和最低氣溫。

import re
from datetime import datetime
from datetime import timedelta
from matplotlib import pyplot as plt
from urllib.request import *

# 定義一個函數(shù)讀取lishi.tianqi.com的數(shù)據(jù)
def get_html(city, year, month):  #①
    url = 'http://lishi.tianqi.com/' + city + '/' + str(year) + str(month) + '.html'
    # 創(chuàng)建請求
    request = Request(url)
    # 添加請求頭
    request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64)' +
        'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36')
    response = urlopen(request)
    # 獲取服務器響應
    return response.read().decode('gbk')

# 定義3個list列表作為展示的數(shù)據(jù)
dates, highs, lows = [], [], []
city = 'guangzhou'
year = '2017'
months = ['01', '02', '03', '04', '05', '06', '07',
    '08', '09', '10', '11', '12']
prev_day = datetime(2016, 12, 31)
# 循環(huán)讀取每個月的天氣數(shù)據(jù)
for month in months:
    html = get_html(city, year, month)
    # 將html響應拼起來
    text = "".join(html.split())
    # 定義包含天氣信息的div的正則表達式
    patten = re.compile('<divclass="tqtongji2">(.*?)</div><divstyle="clear:both">')
    table = re.findall(patten, text)
    patten1 = re.compile('<ul>(.*?)</ul>')
    uls = re.findall(patten1, table[0])
    for ul in uls:
        # 定義解析天氣信息的正則表達式
        patten2 = re.compile('<li>(.*?)</li>')
        lis = re.findall(patten2, ul)
        # 解析得到日期數(shù)據(jù)
        d_str = re.findall('>(.*?)</a>', lis[0])[0]
        try:
            # 將日期字符串格式化為日期
            cur_day = datetime.strptime(d_str, '%Y-%m-%d')
            # 解析得到最高氣溫和最低氣溫
            high = int(lis[1])
            low = int(lis[2])
        except ValueError:
            print(cur_day, '數(shù)據(jù)出現(xiàn)錯誤')
        else:
            # 計算前、后兩天數(shù)據(jù)的時間差
            diff = cur_day - prev_day
            # 如果前、后兩天數(shù)據(jù)的時間差不是相差一天,說明數(shù)據(jù)有問題
            if diff != timedelta(days=1):
                print('%s之前少了%d天的數(shù)據(jù)' % (cur_day, diff.days - 1))
            dates.append(cur_day)
            highs.append(high)
            lows.append(low)
            prev_day = cur_day
# 配置圖形
fig = plt.figure(dpi=128, figsize=(12, 9))
# 繪制最高氣溫的折線
plt.plot(dates, highs, c='red', label='最高氣溫',
    alpha=0.5, linewidth = 2.0)
# 再繪制一條折線
plt.plot(dates, lows, c='blue', label='最低氣溫',
    alpha=0.5, linewidth = 2.0)
# 為兩個數(shù)據(jù)的繪圖區(qū)域填充顏色
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# 設(shè)置標題
plt.title("廣州%s年最高氣溫和最低氣溫" % year)
# 為兩條坐標軸設(shè)置名稱
plt.xlabel("日期")
# 該方法繪制斜著的日期標簽
fig.autofmt_xdate()
plt.ylabel("氣溫(℃)")
# 顯示圖例
plt.legend()
ax = plt.gca()
# 設(shè)置右邊坐標軸線的顏色(設(shè)置為none表示不顯示)
ax.spines['right'].set_color('none')
# 設(shè)置頂部坐標軸線的顏色(設(shè)置為none表示不顯示)
ax.spines['top'].set_color('none')
plt.show()

Python如何讀取網(wǎng)絡數(shù)據(jù)

程序中第 32 行代碼使用正則表達式來獲取包含全部天氣信息的 <div.../> 元素,即圖 1 中數(shù)字 1 所標識的 <div.../> 元素。

程序中第 34 行代碼使用正則表達式來匹配天氣 <div.../> 中沒有屬性的 <ul.../> 元素,即圖 1 中數(shù)字 2 所標識的 <ul.../> 元素。這樣的 <ul.../> 元素有很多個,每個 <ul.../> 元素代表一天的天氣信息,因此,上面程序使用了循環(huán)來遍歷每個 <ul.../> 元素。

程序中第 38 行代碼使用正則表達式來匹配每日天氣 <ul...> 中的 <li.../> 元素,即圖 1 中數(shù)字 3 所標識的 <li.../> 元素。在每個 <ul.../> 元素內(nèi)可匹配到 6 個 <li.../> 元素,但程序只獲取日期、最高氣溫和最低氣溫,因此,程序只使用前三個 <li.../> 元素的數(shù)據(jù)。

以上就是Python如何讀取網(wǎng)絡數(shù)據(jù),小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI