1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python] Webスクレイピング 値取得の完全自動化 -BeautifulSoup-

Last updated at Posted at 2022-11-04

はじめに

前回に続き、Webスクレイピングの自動化について、まとめておく
今回は特に株価に注目してWebスクレイピングをした

環境

windows 10
python version: 3.7.8
Microsoft Edge
Yahoo Finance

Code

import requests
from bs4 import BeautifulSoup

情報の自動取得

def Read_Stock_Price(stock_number: list) -> str:
    data = requests.get(f'https://finance.yahoo.co.jp/quote/{stock_number}.T')
    soup = BeautifulSoup(data.content, 'html.parser')

    # htmlより場所を指定
    price_now = soup.find_all('span', class_="_3rXWJKZF")[0].text
    stock_name =  soup.find_all('h1', class_="_6uDhA-ZV")[0].text

    stock = {'name':stock_name, 'price': price_now}
    return stock

stock_number_list = [2484, 7901, 7203, 6758, 9434, 9433]

f_w = open('price.csv', 'w', encoding='utf-8')
for stock_number in stock_number_list:
    f_w.write(f'{Read_Stock_Price(stock_number)["name"]},
                {Read_Stock_Price(stock_number)["price"]} \n')
f_w.close()
price.csv
(株)出前館, 518 
(株)マツモト, 5,650
トヨタ自動車(株), 2,014.5
ソニーグループ(株), 10,755
ソフトバンク(株), 1,470
KDDI(株), 4,435

指定した6つの株に関して自動で現在の株価を取得した

応用ー完全自動化

def Read_Stock_Price(stock_number: list) -> str:
    data = requests.get(f'https://finance.yahoo.co.jp/quote/{stock_number}.T')
    if str(data.status_code) == '200':
        soup = BeautifulSoup(data.content, 'html.parser')

        price_now = soup.find_all('span', class_="_3rXWJKZF")[0].text
        stock_name = soup.find_all('h1', class_="_6uDhA-ZV")[0].text

        stock = {'name': stock_name, 'price': price_now}
        print(f'{stock_number} succeded')
        return stock
    else:
        print(f'{stock_number} failed')
        return None


stock_number_list = [ i for i in range(1000, 9999)]

f_w = open('price.csv', 'w', encoding='utf-8')
for stock_number in stock_number_list:
    if  Read_Stock_Price(stock_number) != None:
        f_w.write(
        f'{Read_Stock_Price(stock_number)["name"]}, 
          {Read_Stock_Price(stock_number)["price"]} \n')
f_w.close()
terminal
6000 failed
6001 failed
6002 failed
6003 failed
6004 failed
6005 succeded
6005 succeded
6005 succeded
6006 failed
6007 failed
6008 failed
...
price.csv
三浦工業(株), 2,961 
(株)タクマ, 1,213 
(株)ジャパンエンジンコーポレーション, 1,208 
阪神内燃機工業(株), --- 
(株)赤阪鐵工所, 1,430 
ダイハツディーゼル(株), 563 
GMO TECH(株), 1,670 
弁護士ドットコム(株), 2,949 
テクノプロ・ホールディングス(株), 3,785 
アトラグループ(株), 190 
(株)アドベンチャー, 11,320 
....

成功コードが得られたら、情報を保存するように指定した
1個の株価で約0.1秒ほどかかった
マルチスレッドを利用するともっと早くできると思う

まとめ

株コードは1301から9997番まであるようなので、程よく真ん中の範囲の指定して値を取得したが、予め株コードの情報を取得してからの方が結果的に早く終わった可能性も考えられる

関連

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?