【Python/初級者向け/プログラミング】スクレイピングで上場企業の証券コードを自動で取得

はじめに

人気プログラミング言語「Python」を使って日本経済新聞のWEBページへアクセスし、現在上場している企業の証券コードを取得してみました。

環境・使用ツール

<言語>

 Python 3.9

<ライブラリ>

 beautifulsoup4

 requests

<使用ツール>

Visual Studio Code

ソースコード(最終)

import requests
from bs4 import BeautifulSoup as bs
import time

start = time.time()
list_name = []
list_codes = []
def stock_code_acquire(): 
  for i in range(1301, 9995):
    url = "https://www.nikkei.com/nkd/company/?scode=" + str(i)    
    response = requests.get(url)    
    response.encoding = response.apparent_encoding   
    soup = bs(response.text, "html.parser")     
    result_codes = soup.select("#CONTENTS_MAIN > div.m-companyCategory > span.m-companyCategory_text.a-baseLinkStyleType02") 
    for result_code in result_codes:
      code = result_code.text.replace(' ','')[2:6]
      list_codes.append(code)
    print(code)

print(stock_code_acquire())

finish = time.time() - start
print(format(finish))

解説

import requests

from bs4 import BeautifulSoup as bs

import time

→必要なライブラリをインストールしています。標準ライブラリのtime以外は、コマンドでインストールが必要です。事前にプロジェクト直下でpip install requests bs4を行いインストールする必要があります。

※VSCodeでフォルダを開き、「ctrl + @」でターミナルを開くことができます。

start = time.time()

→スクレイピング開始時刻を変数に代入。

list_name = []

list_codes = []

→スクレイピングで取得した値を格納するために空のリストを作成。

def stock_code_acquire():

→関数をしています。

for i in range(1301, 9995):

url = "https://www.nikkei.com/nkd/company/?scode=" + str(i)

→for文でループしています。code以下を1301~9994に値を変えてurlに全値を代入してます。

response = requests.get(url)

→requestsモジュールで該当urlにhttpリクエストを行う。

response.encoding = response.apparent_encoding

→エンコードして文字化けを回避する。

soup = bs(response.text, "html.parser")

→ 解析できる形にパース

result_codes = soup.select("#CONTENTS_MAIN > div.m-companyCategory > span.m-companyCategory_text.a-baseLinkStyleType02")

→select()で該当サイトの取得したいタグを取得

for result_code in result_codes:

code = result_code.text.replace(' ','')[2:6]

list_codes.append(code)

→取得した値をreplace()で整え、list_codeに追加していく。

print(stock_code_acquire())

→作成した関数を実行しています。

finish = time.time() - start

print(format(finish))

→処理にかかった時間を計測し、その秒数を表示しています。

まとめ

スクレイピングができるようになると仕事の幅が劇的に広がります。

また、調べものを自動化することは驚くぐらいの作業時間の削減につながります。

日々の仕事をスマートに!

参考

日本経済新聞:https://www.nikkei.com/nkd/?MsgId=1

Pythonのライブラリ活用例:https://esc-key.net/2021/07/23/%e3%80%90python%e3%80%91python%e3%81%ae%e3%83%a9%e3%82%a4%e3%83%96%e3%83%a9%e3%83%aa%e3%81%be%e3%81%a8%e3%82%81/

【Python/初級者向け/プログラミング】スクレイピングで上場企業の証券コードを自動で取得” に対して1件のコメントがあります。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です