import os import glob import imghdr import openpyxl import cv2 import logging import logging.config import yaml import math with open('logger.yaml',mode= 'r') as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) logger = logging.getLogger('sampleLogger') logger.info('** START imgpaste **') # 定数設定 INPUT_IMG_DIR = '.\\' # 貼り付ける画像を置いておくルートディレクトリ SHEET_TITLE = 'result' # シート名の設定 RESULT_FILE_NAME = '.\\result.xlsx' # 結果を保存するファイル名 # 変数 max_height = [] # 各行の画像の高さの最大値を保持 def get_file_names(set_dir_name): """ ディレクトリ内のファイル名取得(ファイル名のみの一覧を取得) """ file_names = os.listdir(set_dir_name) temp_full_file_names = [os.path.join(set_dir_name, file_name) for file_name in file_names if os.path.isfile(os.path.join(set_dir_name, file_name))] # ファイルかどうかを判定 return temp_full_file_names def attach_img(target_full_file_names): """ 画像を呼び出して、Excelに貼り付け """ #貼り付ける行 set_row_idx = 1 #1画像当たりの行数単位取得 sample_size_img = cv2.imread(target_full_file_names[0]) height, width = sample_size_img.shape[:2] #サイズ取得 tani = math.ceil(height/25) + 2 #18.75ポイント=20ピクセル + 余白 #行の高さ合わせ(18.75ポイント=20ピクセル) img_files_len = len([x for x in target_full_file_names if imghdr.what(x) != None]) for row_height in range(img_files_len * tani): ws.row_dimensions[row_height].height = 18.75 ws.column_dimensions['A'].width = 30 target_full_file_names.sort() # ファイル名でソート for target_file in target_full_file_names: if imghdr.what(target_file) != None: # 画像ファイルかどうかの判定 img = openpyxl.drawing.image.Image(target_file) logger.info(target_file + 'を貼り付け') #ファイル名を設定 cell_address = ws.cell(row=set_row_idx, column=1).coordinate # セルの行列番号から、そのセルの番地を取得 ws[cell_address] = os.path.splitext(os.path.basename(target_file))[0] #imgを貼り付け cell_address = ws.cell(row=set_row_idx, column=2).coordinate # セルの行列番号から、そのセルの番地を取得 img.anchor = cell_address ws.add_image(img) # シートに画像貼り付け set_row_idx += tani #終了メッセージ cell_address = ws.cell(row=set_row_idx, column=1).coordinate # セルの行列番号から、そのセルの番地を取得 ws[cell_address] = 'END' # ワークブック設定 wb = openpyxl.Workbook() ws = wb.worksheets[0] # 1番目のシートを編集対象にする ws.title = SHEET_TITLE # 1番目のシートに名前を設定 file_lists = get_file_names(INPUT_IMG_DIR) attach_img(file_lists) # 画像貼り付け設定 # ファイルへの書き込み wb.save(RESULT_FILE_NAME) #終了 logger.info('** END imgpaste **')
カテゴリー: 投資
version: 1 formatters: simple: format: '%(asctime)s-%(name)s-%(levelname)s-%(message)s' handlers: console_handler: class: logging.StreamHandler level: INFO formatter: simple stream: ext://sys.stdout file_handler: class: logging.FileHandler level: INFO filename: scripts.log formatter: simple loggers: sampleLogger: level: DEBUG handlers: [console_handler, file_handler] propagate: no root: level: DEBUG handlers: [console_handler, file_handler]
import logging import logging.config import yaml import cv2 import os import imghdr import shutil with open('logger.yaml',mode= 'r') as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) logger = logging.getLogger('sampleLogger') logger.info('** START resize **') 画像ファイルのlistを取得 tmp_files = [x for x in os.listdir() if os.path.isfile(x)] files = [x for x in tmp_files if imghdr.what(x) != None] logger.info(f'tmp >> {files}') バックアップ if not os.path.exists('tmp'): os.makedirs('tmp') for bkfile in files: shutil.copy2(bkfile,'tmp') logger.info('バックアップ完了') リサイズ for filename in files: logger.info(f'{filename} resize 開始') img = cv2.imread(filename) height = img.shape[0] width = img.shape[1] width = int(width0.5) height = int(height0.5) img2 = cv2.resize(img, (width, height)) cv2.imwrite(filename, img2) logger.info(f'{filename} resize 完了') logger.info('** END resize **')
[Common]
OUT_PATH = D:\data\stock\
DRIVER_PATH = D:\data\python\selenium\chromedriver.exe
ACCOUNT_NAME = ken39rai@ybb.ne.jp
ACCOUNT_PASS = sakusakusakusaku
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.keys import Keys
import time
import os
import configparser
import Utils
def main():
#処理時間計測
start = time.time()
printmessage('処理開始')
#コンフィグ取得
cf = configparser.ConfigParser()
cf.read("config.ini")
out_path = cf.get("Common", "OUT_PATH")
name = cf.get("Common", "ACCOUNT_NAME")
passwd = cf.get("Common", "ACCOUNT_PASS")
#初期処理
#銘柄取得
with open(os.path.join('D:\data\stock','TICKER_SYMBOL.txt'),'r') as f:
symboldatas = f.read().splitlines()
symbols = []
filenames =[]
for s in symboldatas:
tmp = s.split(',')
symbols.append(tmp[1])
filenames.append([tmp[1],tmp[0]+'_'+tmp[1]])
#日付取得
strnow = Utils.getDate(time.localtime())
#フォルダ作成
Utils.setup(symbols)
printmessage('初期処理終了')
try:
#ドライバ起動
option = webdriver.ChromeOptions()
option.add_argument('--window-size=1600,1000')
option.add_argument('--ignore-certificate-errors')
option.add_argument('--ignore-ssl-errors')
option.add_argument('--headless')
driver = webdriver.Chrome("D:\data\python\\selenium\chromedriver.exe",options=option)
driver.implicitly_wait(20)
wait = WebDriverWait(driver,10)
printmessage('ドライバ起動終了')
#ログイン
driver.get("https://finance.yahoo.com/")
driver.find_element_by_xpath('//*[@id="header-signin-link"]').click()
driver.find_element_by_xpath('//*[@id="login-username"]').send_keys(name)
driver.find_element_by_xpath('//*[@id="login-signin"]').click()
time.sleep(0.5)
driver.find_element_by_xpath('//*[@id="login-passwd"]').send_keys(passwd)
driver.find_element_by_xpath('//*[@id="login-signin"]').click()
time.sleep(0.5)
printmessage('ログイン完了')
#銘柄チャート画面遷移、全画面表示
driver.find_element_by_xpath('//*[@id="yfin-usr-qry"]').send_keys('U')
time.sleep(0.5)
driver.find_element_by_xpath('//*[@id="yfin-usr-qry"]').send_keys(Keys.ENTER)
time.sleep(0.5)
driver.find_element_by_link_text('Full screen').click()
time.sleep(1)
#期間設定、指標設定
driver.find_element_by_xpath('//span[contains(text(),"1Y")]/ancestor::button').click()
time.sleep(0.5)
driver.find_element_by_xpath('//span[text()="Line"]').click()
time.sleep(0.5)
driver.find_element_by_xpath('//span[contains(text(),"Candle")]/ancestor::button').click()
time.sleep(0.5)
#移動平均線設定(50日)
driver.find_element_by_xpath('//span[text()="Indicators"]').click()
driver.find_element_by_xpath('//button[contains(text(),"Moving Average")]').click()
time.sleep(0.5)
driver.find_element_by_xpath('//table[@role="presentation"]/tbody/tr/td/input[@type="text"]').clear()
driver.find_element_by_xpath('//table[@role="presentation"]/tbody/tr/td/input[@type="text"]').send_keys('50')
driver.find_element_by_xpath('//span[contains(text(),"Save")]/ancestor::button').click()
time.sleep(0.5)
#移動平均線設定(200日)
driver.find_element_by_xpath('//span[text()="Indicators"]').click()
driver.find_element_by_xpath('//button[contains(text(),"Moving Average")]').click()
time.sleep(0.5)
driver.find_element_by_xpath('//table[@role="presentation"]/tbody/tr/td/input[@type="text"]').clear()
driver.find_element_by_xpath('//table[@role="presentation"]/tbody/tr/td/input[@type="text"]').send_keys('200')
driver.find_element_by_xpath('//span[contains(text(),"Save")]/ancestor::button').click()
time.sleep(0.5)
#移動平均線設定(20日)
driver.find_element_by_xpath('//span[text()="Indicators"]').click()
driver.find_element_by_xpath('//button[contains(text(),"Moving Average")]').click()
time.sleep(0.5)
driver.find_element_by_xpath('//table[@role="presentation"]/tbody/tr/td/input[@type="text"]').clear()
driver.find_element_by_xpath('//table[@role="presentation"]/tbody/tr/td/input[@type="text"]').send_keys('20')
driver.find_element_by_xpath('//span[contains(text(),"Save")]/ancestor::button').click()
printmessage('指標設定完了')
#各銘柄毎スクリーンショット
#filenames : [0]ティッカーシンボル、[1]優先度+ティッカーシンボル
for symbol in filenames:
driver.find_element_by_name('s').send_keys(symbol[0])
time.sleep(1)
#driver.find_element_by_xpath('//*[@data-icon="search"]/ancestor::button').click()
driver.find_element_by_name('s').send_keys(Keys.ENTER)
time.sleep(3)
WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located)
time.sleep(3)
#if driver.find_element_by_xpath('//div[@class="stx_jump_today home"]'):
# if len(driver.find_element_by_xpath('//div[@class="stx_jump_today home"]'))>0:
# driver.find_element_by_xpath('//div[@class="stx_jump_today home"]').click()
# time.sleep(0.5)
driver.find_element_by_name('s').clear()
filename = strnow + '_' + symbol[1] + '.png'
symboloutfile = os.path.join(out_path,'symbol',symbol[0],filename)
datefile = os.path.join(out_path,'date',strnow,filename)
driver.get_screenshot_as_file(symboloutfile)
driver.get_screenshot_as_file(datefile)
printmessage(symbol[0] + '取得完了')
print(str(len(filenames)) + '件の銘柄取得、正常終了しました。')
except Exception as e:
print('異常終了しました。')
finally:
elapsed_time = time.time() - start
print ("elapsed_time:{0}".format(elapsed_time) + "[sec]")
driver.quit()
def printmessage(str):
print("*"*20)
print(str.center(20))
print("*"*20)
if __name__ == "__main__":
main()
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.keys import Keys
import time
import os
import configparser
import Utils
def main():
#処理時間計測
start = time.time()
printmessage('処理開始')
#コンフィグ取得
cf = configparser.ConfigParser()
cf.read("config.ini")
out_path = cf.get("Common", "OUT_PATH")
name = cf.get("Common", "ACCOUNT_NAME")
passwd = cf.get("Common", "ACCOUNT_PASS")
#初期処理
#銘柄取得
with open(os.path.join('D:\data\stock','TICKER_SYMBOL.txt'),'r') as f:
symboldatas = f.read().splitlines()
symbols = []
filenames =[]
for s in symboldatas:
tmp = s.split(',')
symbols.append(tmp[1])
filenames.append([tmp[1],tmp[0]+'_'+tmp[1]])
#日付取得
strnow = Utils.getDate(time.localtime())
#フォルダ作成
Utils.setup(symbols)
printmessage('初期処理終了')
カテゴリー
Hello world!
WordPress へようこそ。こちらは最初の投稿です。編集または削除し、コンテンツ作成を始めてください。