📘
Python web crawler note
  • Introduction
  • 1. 環境安裝與爬蟲的基本
  • 1.1 環境安裝
  • 1.2 IDE設定
  • 1.3 一隻很原始的爬蟲
  • 1.4 幫爬蟲裝煞車
  • 2. 用BeautifuSoup來分析網頁
  • 2.1 BeautifulSoup範例 - 1
  • 2.2 BeautifulSoup說明
  • 2.3 BeautifulSoup範例 - 2
  • 2.4 加入Regular Expression
  • 2.5 Dcard今日十大熱門文章
  • 3. 更多實際的應用
  • 3.1 PTT八卦版今日熱門文章
  • 3.2 Yahoo奇摩電影本週新片
  • 3.3 蘋果日報/自由時報今日焦點
  • 3.4 Google Finance 個股資訊
  • 3.5 Yahoo奇摩字典
  • 4. 基於API的爬蟲
  • 4.1 八卦版鄉民從哪來?
  • 4.2 Facebook Graph API
  • 4.3 imdb電影資訊查詢
  • 4.4 Google Finance API
  • 4.5 台灣證券交易所API
  • 5. 資料儲存
  • 5.1 痴漢爬蟲(PTT表特版下載器)
  • 5.2 儲存成CSV檔案
  • 5.3 儲存至SQLite
  • 6. 不同編碼/文件類型的爬蟲
  • 6.1 非UTF-8編碼的文件
  • 6.2 XML文件
  • 7. 比價爬蟲
  • 7.1 momo購物網爬蟲
  • 7.2 PChome 24h API爬蟲
  • 7.3 比價圖表程式
  • 8. 處理POST請求/登入頁面
  • 8.1 空氣品質監測網
  • 9. 動態網頁爬蟲
  • 9.1 台銀法拍屋資訊查詢
  • 10. 自然語言處理
  • 10.1 歌詞頻率與歌詞雲
Powered by GitBook
On this page

Was this helpful?

7.3 比價圖表程式

搜集了一定數量的資料後, 就可以用圖表來展示結果了.

import json
import os
from matplotlib import pyplot as plt


def get_avg_price(json_data):
    sum = 0
    for item in json_data:
        sum += int(item['price'])
    return sum/len(json_data)


def main():
    json_files = [f for f in os.listdir('json')
                  if os.path.isfile(os.path.join('json', f)) and f.endswith('.json')]

    avg_prices_momo = dict()
    avg_prices_pchome = dict()

    for json_file in json_files:
        with open(os.path.join('json', json_file), 'r', encoding='UTF-8') as file:
            data = json.load(file)
            date = data['date']
            if data['store'] == 'momo':
                avg_prices_momo[date] = get_avg_price(data['items'])
            elif data['store'] == 'pchome':
                avg_prices_pchome[date] = get_avg_price(data['items'])

    keys = avg_prices_momo.keys()
    dates = sorted(keys)
    print('momo')
    for date in dates:
        print(date, int(avg_prices_momo[date]))
    print('pchome')
    for date in dates:
        print(date, int(avg_prices_pchome[date]))

    # x-axis
    x = [int(i) for i in range(len(dates))]
    plt.xticks(x, dates)  # 將 x-axis 用字串標註
    price_momo = [avg_prices_momo[d] for d in dates]  # y1-axis
    price_pchome = [avg_prices_pchome[d] for d in dates]  # y2-axis
    plt.plot(x, price_momo, marker='o', linestyle='solid')
    plt.plot(x, price_pchome, marker='o', linestyle='solid')
    plt.legend(['momo', 'pchome'])
    # specify values on ys
    for a, b in zip(x, price_momo):
        plt.text(a, b, str(int(b)))
    for a, b in zip(x, price_pchome):
        plt.text(a, b, str(int(b)))
    plt.show()


if __name__ == '__main__':
    main()

結果輸出:

Previous7.2 PChome 24h API爬蟲Next8. 處理POST請求/登入頁面

Last updated 5 years ago

Was this helpful?

原始碼

點我