很多時候,程式並不能直接展示本地檔案中的資料,此時需要程式讀取網路資料,並展示它們。
前面已經介紹了 python 的網路支援庫 urllib,通過該庫下的 request 模組可以非常方便地向遠端傳送 http 請求,獲取伺服器響應。因此,本程式的思路是使用 urllib.request 向 lishi.tianqi.com 傳送請求,獲取該**的響應,然後使用 python 的 re 模組來解析伺服器響應,從中提取天氣資料。
本程式將會通過網路讀取 站點的資料,並展示 2017 年廣州的最高氣溫和最低氣溫。import re
from datetime import datetime
from datetime import timedelta
from matplotlib import pyplot as plt
from urllib.request import *
# 定義乙個函式讀取lishi.tianqi.com的資料
def get_html(city, year, month): #①
url = '/' + city + '/' + str(year) + str(month) + '.html'
# 建立請求
request = request(url)
# 新增請求頭
request.add_header('user-agent', 'mozilla/5.0 (windows nt 10.0; wow64)' +
response = urlopen(request)
# 獲取伺服器響應
return response.read().decode('gbk')
# 定義3個list列表作為展示的資料
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)
# 迴圈讀取每個月的天氣資料
for month in months:
html = get_html(city, year, month)
# 將html響應拼起來
text = "".join(html.split())
# 定義包含天氣資訊的div的正規表示式
patten = re.compile('(.*?)
python如何獲取網路資料
python 內建了 sockets 可以實現與網路連線並通過 python 提取資料的功能。socket 是可以提供雙向連線的,我們可以對同乙個 socket 進行讀寫操作。比方說,a 對 socket 寫入資訊,並且將其傳送給 sock 連線另一端 b 那麼 b 讀取 socket 的內容就可以...
獲取網路資料
j2se實現網路的獲取 btn text 顯示網路 android layout width fill parent android layout height wrap content android text string btn text android id id showbtn andro...
網路獲取資料
1 http協議定義 www是以internet作為傳輸媒介的乙個應用系統,www網上基本的傳輸單位是web網頁。www的工作是基於客戶機 伺服器計算模型,由web瀏覽器和web伺服器構成,兩者之間採用超文字傳輸協議http進行通訊。http協議時基於tcp ip協議之上的協議,是web瀏覽器和we...