Pythonの勉強中です。
PythonからSeleniumを使ってGoogle Chromeを自動操作して
指定サイトにcsvファイルをアップロードするものす。
詳細はブログに書きました。
https://tbshiki.com/pythonstudy004/
構成
pythonstudy/ ├ sample.py ├ chromedriver.exe ├ csvlist.txt ├ finmassege.txt └ csv/ └[アップロードしたい.csv]
プログラム
sample.pyfrom selenium import webdriver from selenium.webdriver.common.alert import Alert import time import os import wx import sys #サイトログインページ情報とログイン情報をまとめる TOP_URL = "example.com" UPLOAD_URL = "http://hogehoge.example/" ID = "id" PASSWORD = "password" #ディレクトリを取得 dir_name = (os.path.dirname(__file__)) dir_name = dir_name.replace('\\', '/') #Windows用?に\を/に置換 #完了メッセージ表示用のwxPython wx_app = wx.App() #ブラウザ読み込み driver = webdriver.Chrome("./chromedriver.exe") #chromedriver.exe読み込み driver.set_page_load_timeout(600) #ページロード最大600秒 driver.get(TOP_URL) #chrome起動→ログインページに移動 time.sleep(1) #ログイン id = driver.find_element_by_name("loginid") id.send_keys(ID) password = driver.find_element_by_name("password") password.send_keys(PASSWORD) time.sleep(1) #ログインボタンをクリック login_button = driver.find_element_by_name("login") login_button.click() time.sleep(1) #csv一覧のテキストファイルを読み込みで開いてリストに csv_list_file = open('./csvlist.txt', 'r') #csvファイルの一覧テキストファイルを読み込み csv_list = csv_list_file.readlines() csv_list_file.close() #csv一覧からできたリスト分繰り返し for i in range(len(csv_list)): #csvを読み込ませるページに移動 driver.get(UPLOAD_URL) time.sleep(1) #ファイルの絶対パスを変数に ファイルは/csv/にある file_choice_str = dir_name + '/csv/' + csv_list[i].rstrip() #ファイル読み込み file_choice = driver.find_element_by_name("fileupload") file_choice.send_keys(file_choice_str) time.sleep(1) #アップロードボタンをクリック now_upload = driver.find_element_by_class_name("uploadbotton") now_upload.click() time.sleep(1) #読み込み停止時再実行の為の変数設定 loop_count = 0 #読み込み停止時再実行用繰り返し while True: #再実行しすぎを防止 loop_count += 1 if loop_count >= 3: #エラーメッセージボックスを表示 wx.MessageBox('3回失敗', 'Python') #エラーが続いたのでプログラムを終了 sys.exit() try: #ダイアログの表示取得 alert_text = Alert(driver).text #取得した文字列を表示 print(alert_text) #ダイアログのOKを選択 Alert(driver).accept() time.sleep(1) #whileを抜ける break except: print("読み込み停止") #ブラウザに表示されたメッセージを取得 fin_massege = driver.find_element_by_class_name("massege") fin_massege_str = fin_massege.text #文字列として変数に代入 #複数行の場合改行を半角スペースに置換して1行に、行末に改行 fin_massege2 = csv_list[i].rstrip() + fin_massege_str.replace("\n"," ") + "\n" print(fin_massege2) #完了ログ用テキストを開いて追記 fin_massege_txt = open('./finmassege.txt', 'a') fin_massege_txt.write(fin_massege2) fin_massege_txt.close() #読み込みが完了したcsvをテキストから削除して上書き(実際には作り直し) csv_list_file = open('./csvlist.txt', 'r') #読み込み専用で開く csv_list2 = csv_list_file.readlines() #行ごとにリスト化 del csv_list2[0] #1行目にあたるリスト0番目を削除 csv_list_file = open('./csvlist.txt', 'w') #書き込み専用で開く(この時にテキストファイルは空白になる) csv_list_file.writelines(csv_list2) #0番目を削除したリストをテキストファイルに csv_list_file.close() #テキストファイルを終了 #繰り返しの為の初期化 alert_text = "" #ブラウザを閉じる driver.close() #完了メッセージボックスを表示 wx.MessageBox('完了', 'Python')