-- coding: utf-8 - -
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import pandas as pd
import schedule
import time
from datetime import datetime as dt
import gspread
import json
def sisankaki():
options = Options()
# ヘッドレスモード(chromeを表示させないモード)
options.add_argument('--headless')
driver = webdriver.Chrome(executable_path='XXXX', options=options)
driver.get('https://www.sbisec.co.jp/ETGate')
#スクリーンショットをとって確認することも可
#driver.save_screenshot('sbi.png')
# ユーザーネームとパスワードを設定
username = "XXX"
password = "XXX"
# ユーザーネームテキストボックスを選択
user_id = driver.find_element_by_id("user_input")
# ユーザーネームを入力
user_id.find_element_by_name("user_id").send_keys(username)
# パスワードテキストボックスを選択
user_pass = driver.find_element_by_id("password_input")
# パスワードを入力
user_pass.find_element_by_name("user_password").send_keys(password)
# ログインを押下
driver.find_element_by_class_name("ov").click()
# 口座管理に遷移
driver.find_element_by_xpath("/html/body/div[1]/div[1]/div[2]/div/ul/li[3]/a/img").click()
#print(driver.current_url)
# 文字コードをUTF-8に変換
html = driver.page_source.encode('utf-8')
# BeautifulSoupでパース
soup = BeautifulSoup(html, "html.parser")
table = soup.find_all("table", border="0", cellspacing="0", cellpadding="0", width="340")
#pd.read_html()はListに格納されて戻されることに注意
df_table = pd.read_html(str(table))[9]
print(df_table)
print(type(df_table))
## 必要な行・列のみ抽出(信用ポジがある場合iloc[9,1]にする)
sousisan = df_table.iloc[8, 1]
print(sousisan)
# ブラウザーを閉じる
driver.quit()
#####ここからスプレッドシート操作#####
#ServiceAccountCredentials:Googleの各サービスへアクセスできるservice変数を生成します。
from oauth2client.service_account import ServiceAccountCredentials
#2つのAPIを記述しないとリフレッシュトークンを3600秒毎に発行し続けなければならない
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
#認証情報設定
#ダウンロードしたjsonファイル名をクレデンシャル変数に設定(秘密鍵、Pythonファイルから読み込みしやすい位置に置く)
credentials = ServiceAccountCredentials.from_json_keyfile_name('XXX', scope)
#OAuth2の資格情報を使用してGoogle APIにログインします。
gc = gspread.authorize(credentials)
#共有設定したスプレッドシートキーを変数[SPREADSHEET_KEY]に格納する。
SPREADSHEET_KEY = 'XXX'
#共有設定したスプレッドシートのシート1を開く
worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1
#A4セルの値に表示させる
worksheet.update_cell(3,1, sousisan)
ima = dt.now()
imastr = ima.strftime('%H:%M:%S')
print(imastr)
print("I'm writing...")
sisankaki()
定期実行するジョブをライブラリに登録(実行時間も管理する)
#schedule.every(15).minutes.do(sisankaki)
登録したジョブを実行させるための処理?
#while True:
schedule.run_pending()
time.sleep(1)
#もし15:15こえたらブレイク
if (15 - dt.now().hour <=0) and (15 - dt.now().minute <= 0) :
print('終了します。')
break