LoginSignup
0
4

More than 3 years have passed since last update.

プログラミング歴1ヶ月 PythonでNYダウの株価を抽出!

Last updated at Posted at 2020-02-04

初めまして、Kayです。

投資をやっていまして、今年の1月からPythonにフロンティアを感じ、投資に応用出来ないかということで、ようやくYahooファイナンスの株価の抽出くらいまでたどり着きました。
というわけで、プログラミング歴は1ヶ月です(笑)
github↓
https://github.com/Kay-Hatsune/NY-Dow/blob/master/dow.py

使用したもの

言語:Python3

ライブラリ:urllib、BeautifulSoup

MacBook Pro

BeautifulSoupをインストールする

shell.sh
$ pip3 install beautifulsoup

自分の場合、MacOSだったので、pip3インストールとなりました。windowsの人は違うと思うので注意してください。

Pythonのコード

dow.py
import urllib.request
import ssl
from bs4 import BeautifulSoup

url = "https://finance.yahoo.co.jp/quote/%5EDJI"

ssl._create_default_https_context = ssl._create_unverified_context

html = urllib.request.urlopen(url)

soup = BeautifulSoup(html, "html.parser")

p = soup.find_all("p")

dow = ""
for tag in p:
    try:
        string_ = tag.get("class").pop(0)

        if string_ in "wlbmIy9W":
            dow = tag.string
            break
    except:
        pass

print(dow)

BeautifulSoupでYahooファイナンスからurlを引っ張ってきます。

株価がpというところに入っているのでhtmlデータの中のpを検索します。

pの中のclass="wlbmIy9W"の場所を特定するようにfor文とtry except文で構築する。

ちなみに、サイトを右クリックで検証を押すと、簡単に抽出箇所を特定できます。
スクリーンショット 2020-02-04 18.51.58.png

Python3ではSSL証明書が必要になるのが注意点

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

Python3ではこのコードを書き込む必要があります。
書かないと必ずエラーになります。
もしかしたらPython2では必要ないかもしれません。

抽出完了

shell.sh
$ python dow.py

>>>28,399.81

ようやく抽出完了です。5時間もかかりました(笑)
今後はもっと発展させていきたいですね。:stuck_out_tongue_winking_eye:

参考にさせていただいた記事

こちらの方がもっと発展したコードを書いているので必読です!

Python Webスクレイピング 実践入門

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4