前提・実現したいこと
Anacondaをインストールし、
spyderでwindows上にPython環境を作り、Seleniumで
スクレイピングのソースコードがあります。
プログラムの内容は、スクレイピングで
Gmail APIを利用していて、
10秒毎にGmailアカウントを閲覧し、メールの件名に、
指定した文字列のメール受信があった場合は、
自動的にブラウザを起動して、証券会社の口座へログインし、
特定のブラウザ操作を行うというものです。
しかし起動して、放置しておくと、たまに下記のようなエラーが出て、
プログラムが止まってしまっています。
原因と対処法、エラーが出てもプログラムが止まらないようにしたいです。
発生している問題・エラーメッセージ
2018/06/15 04:07:10 waiting... 2018/06/15 04:07:21 waiting... 2018/06/15 04:07:33 waiting... 2018/06/15 04:07:44 waiting... 2018/06/15 04:07:56 waiting... Traceback (most recent call last): File "<ipython-input-5-a859b0451739>", line 1, in <module> runfile('C:/Users/masa/Documents/Auto_Trading_System_shinki_sashine.py', wdir='C:/Users/masa/Documents') File "C:\Users\masa\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\masa\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/masa/Documents/Auto_Trading_System_shinki_sashine.py", line 58, in <module> info=fetch_inbox() File "C:/Users/masa/Documents/Auto_Trading_System_shinki_sashine.py", line 33, in fetch_inbox results = service.users().messages().list(userId='me', labelIds='INBOX', maxResults=10).execute() File "C:\Users\masa\Anaconda3\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\masa\Anaconda3\lib\site-packages\googleapiclient\http.py", line 841, in execute raise HttpError(resp, content, uri=self.uri) HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10&alt=json returned "Bad Request">
該当のソースコード
# -*- coding: utf-8 -*- #!/usr/bin/python """ Created on Wed Apr 17 23:24:27 2018 @author: Starwars """ from __future__ import print_function import time from datetime import datetime from datetime import date from httplib2 import Http from googleapiclient import sample_tools from apiclient import discovery from apiclient.discovery import build from oauth2client import client from oauth2client import tools from oauth2client import file from oauth2client.file import Storage from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select import dateutil.parser as parser SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' store = file.Storage('C:\Users\masa\Documents\credentials-gmail.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) def fetch_inbox(): output=[] results = service.users().messages().list(userId='me', labelIds='INBOX', maxResults=10).execute() for msg in results['messages']: topid = msg['id'] msg = service.users().messages().get(userId='me', id=topid).execute() payld = msg['payload'] headr = payld['headers'] for k in headr: if k['name']=='Date': temp_date=(parser.parse(k['value'])).strftime("%Y/%m/%d %H:%M:%S") for j in headr: if j['name']=='From': temp_from=j['value'] for i in headr: if i['name']=='Subject': temp_subject=i['value'] output.append((temp_date, temp_from, temp_subject, msg['snippet'])) # print(msg['snippet']) return(output) # シグナル検知で打診で成行して、3回ナンピンします。 # 1、買いbtn1 売りbtn2指定 2、ATR指定 3、枚数(numbers)指定 print(datetime.today().strftime("%Y/%m/%d %H:%M:%S"),"先物自動エントリーシステムを起動しました") judge=False while judge==False: info=fetch_inbox() for i in range(len(info)): dt1=datetime.today() dt2=datetime.strptime(info[i][0],"%Y/%m/%d %H:%M:%S") delta=dt1-dt2 if info[i][2]=='FW: Trend Beam' and delta.seconds<60: print(datetime.today().strftime("%Y/%m/%d %H:%M:%S"),"ただ今、MT4より売買指示のメールを受信しました") judge=True if judge==False: print(datetime.today().strftime("%Y/%m/%d %H:%M:%S"),"waiting...") time.sleep(10) if judge==True: print(datetime.today().strftime("%Y/%m/%d %H:%M:%S"),"これより先物自動エントリーの処理を開始します") user_id="00XXXXXX" user_password="ATXXXXXXXXX" temp_path=r"C:\Users\masa\Documents\chromedriver.exe" #ナンピンの1回あたりの枚数を指定 numbers="1" driver = webdriver.Chrome(temp_path) driver.implicitly_wait(60) driver.get("https://s10.kabu.co.jp/_mem_bin/members/login.asp?/Members/") driver.find_element_by_name("SsLogonUser").send_keys(user_id) driver.find_element_by_name("SsLogonPassword").send_keys(user_password) driver.find_element_by_name("image1").click() driver.implicitly_wait(60) driver.find_element_by_name("nav_g_02").click() driver.implicitly_wait(60) #「先物タブ」をクリック driver.find_element_by_xpath('/html/body/table[3]/tbody/tr[1]/td[1]/table/tbody/tr/td[13]/a/div').click() driver.implicitly_wait(60) #ラージ現在価格の取得 sahine = driver.find_element_by_xpath('//*[@id="BoardMainPanel"]/div[1]/table[2]/tbody/tr[2]/td[2]/span') # ATRを指定 ※売りエントリーの場合はマイナス表記で ATR = -20 #ナンピンの指値の計算 x = (int(sahine.text)-(ATR)) y = (int(sahine.text)-(ATR)-(ATR)) z = (int(sahine.text)-(ATR)-(ATR)-(ATR)) print(x) print(y) print(z) #「先物タブ」をクリック driver.find_element_by_xpath('/html/body/table[3]/tbody/tr[1]/td[1]/table/tbody/tr/td[13]/a/div').click() #ページ上部から16番目のa class="openinput"をクリックさせる driver.find_elements_by_css_selector('a.openinput')[15].click() #買いbtn1 売りbtn2 driver.find_element_by_xpath("//*[@id='orderInput_btn2']").click() #「数量」に1を入力 driver.find_element_by_name("Qty").send_keys(numbers) #「成行マーケットオーダー」 をクリック driver.find_element_by_xpath('/html/body/table[4]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/form/div/table[5]/tbody/tr/td/table/tbody/tr/td[1]/table[1]/tbody/tr[3]/td[2]/table[2]/tbody/tr/td[1]/label').click() #「確認画面へ」をクリック driver.find_element_by_xpath('/html/body/table[4]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/form/div/table[5]/tbody/tr/td/table/tbody/tr/td[1]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/input').click() #「注文する」をクリック driver.find_element_by_xpath('//*[@id="form2"]/div/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody/tr/td[3]/input[1]').click() #「先物タブ」をクリック driver.find_element_by_xpath('/html/body/table[3]/tbody/tr[1]/td[1]/table/tbody/tr/td[13]/a/div').click() #ページ上部から16番目のa class="openinput"をクリックさせる driver.find_elements_by_css_selector('a.openinput')[15].click() # 買いbtn1 売りbtn2 driver.find_element_by_xpath("//*[@id='orderInput_btn2']").click() #「数量」に1を入力 driver.find_element_by_name("Qty").send_keys(numbers) # 指値にチェック driver.find_element_by_xpath("//*[@id='orderInput_btn3']").click() # 指値の値段を入力 driver.find_element_by_name("sashineConditions.Price").send_keys(x) #「確認画面へ」をクリック driver.find_element_by_xpath('/html/body/table[4]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/form/div/table[5]/tbody/tr/td/table/tbody/tr/td[1]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/input').click() #「注文する」をクリック driver.find_element_by_xpath('//*[@id="form2"]/div/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody/tr/td[3]/input[1]').click() #「先物タブ」をクリック driver.find_element_by_xpath('/html/body/table[3]/tbody/tr[1]/td[1]/table/tbody/tr/td[13]/a/div').click() #ページ上部から16番目のa class="openinput"をクリックさせる driver.find_elements_by_css_selector('a.openinput')[15].click() # 買いbtn1 売りbtn2 driver.find_element_by_xpath("//*[@id='orderInput_btn2']").click() #「数量」に1を入力 driver.find_element_by_name("Qty").send_keys(numbers) # 指値にチェック driver.find_element_by_xpath("//*[@id='orderInput_btn3']").click() # 指値の値段を入力 driver.find_element_by_name("sashineConditions.Price").send_keys(y) #「確認画面へ」をクリック driver.find_element_by_xpath('/html/body/table[4]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/form/div/table[5]/tbody/tr/td/table/tbody/tr/td[1]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/input').click() #「注文する」をクリック driver.find_element_by_xpath('//*[@id="form2"]/div/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody/tr/td[3]/input[1]').click() #「先物タブ」をクリック driver.find_element_by_xpath('/html/body/table[3]/tbody/tr[1]/td[1]/table/tbody/tr/td[13]/a/div').click() #ページ上部から16番目のa class="openinput"をクリックさせる driver.find_elements_by_css_selector('a.openinput')[15].click() # 買いbtn1 売りbtn2 driver.find_element_by_xpath("//*[@id='orderInput_btn2']").click() #「数量」に1を入力 driver.find_element_by_name("Qty").send_keys(numbers) # 指値にチェック driver.find_element_by_xpath("//*[@id='orderInput_btn3']").click() # 指値の値段を入力 driver.find_element_by_name("sashineConditions.Price").send_keys(z) #「確認画面へ」をクリック driver.find_element_by_xpath('/html/body/table[4]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/form/div/table[5]/tbody/tr/td/table/tbody/tr/td[1]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/input').click() #「注文する」をクリック driver.find_element_by_xpath('//*[@id="form2"]/div/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody/tr/td[3]/input[1]').click() time.sleep(30) #driver.close()
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。