2017年9月22日金曜日

Raspberry Pi3で、コンソールからpygameを使用して画面表示に挑戦(その3)

この記事の続き。

単純に画像ファイルを表示するだけでは、変化が無く面白くないので、BeautifulSoupを使ってWebの画像とデータを表示するものを作成してみました。

Web scrapingは、個人利用か検索用に使用するに留めるべき、マナーがありますのでご利用は計画的に。

今回作成したコードは、Raspberryで個人的に閲覧できるようにしたものです。
ご指摘などございましたらコメント下さい。

#!/usr/bin/python
# coding: UTF-8

import pygame
import urllib2
from time import sleep
from bs4 import BeautifulSoup
from PIL import Image
import cStringIO

def getZaifxChart():
    # urlからhtmlを読み込み、BeautifulSoupで処理する。
    url = "http://zai.diamond.jp/fx?time=1d#charttop"
    html = urllib2.urlopen(url).read()
    soup  = BeautifulSoup(html,"html.parser")
    tagDiv = soup.find_all("div",class_="world-chart-main2 clearfix")

    listTitle  = []
    listNumber = []
    listUrl    = []
    listKey    = []
    # タイトル、URLを抽出する。
    for items in tagDiv:
        for item in items.find_all("div",class_="money-title2 clearfix"):
            for itemTitle in item.find_all("span",class_="chart-title"): # title
                listTitle.append(itemTitle.get_text().encode('utf_8'))
            for itemNumber in item.find_all("span",class_="chart-number"): # Number
                listNumber.append(itemNumber.get_text().split(" ")[0].encode('utf_8'))
        for item in items.find_all("img",class_="refresh-element"): # url,key
            listUrl.append(item["src"])
            listKey.append(item["alt"])

    # PIL で画像を処理する(拡大)。
    listChartUrl = []
    for i in range(0,len(listTitle)):
        # タイトル、価格、アドレス、キー
        listChartUrl.append([listTitle[i],listNumber[i],listUrl[i],listKey[i]])

    return listChartUrl

def main():
    #初期設定
    dSize = (720,480)
    colorBG   = (0,0,0)
    colorFont = (255,255,255)
    # pygame初期設定
    pygame.init()
    lcd = pygame.display.set_mode(dSize)
    lcd.fill(colorBG)
    txtfont = pygame.font.Font("font/tihayagothic.ttf",40)

    # チャートを表示する
    listChartUrl = getZaifxChart() # チャートのURLを取得
    for rows in listChartUrl:
        # urlから画像を読み込みPILでオープンする
        imageFile = cStringIO.StringIO(urllib2.urlopen(rows[2]).read())
        img = Image.open(imageFile).convert("RGB")
        x,y = img.size # サイズを取得する
        imgRe= img.resize((int(x*3.5),int(y*3.5)))
        # 画像データをpygameフォーマットに変換
        imggm = pygame.image.fromstring(imgRe.tobytes(),imgRe.size,imgRe.mode).convert()
        # テキストを書き出す
        fonttext  = txtfont.render(rows[0].decode('utf-8')+"  "+rows[1].decode('utf-8'),False,colorFont,colorBG)
        # 画面に画像を描画する
        lcd.fill(colorBG)
        lcd.blit(imggm,(70,10))
        lcd.blit(fonttext,(75,425))
        pygame.display.update()
        sleep(2)
main()

0 件のコメント:

コメントを投稿

2年ぶりに更新

 最後の記事が21年3月でしたので、27ヶ月ぶり。 2020年頃から始まったコロナ禍から在宅ワークがなくなり、通常運転に慣れてきた頃。 そろそろ新しい趣味を探していこうと思っています。 さて何するかな。。。