import sys
from selenium import webdriver
import urllib
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import os
import time

def process_one():
    global driver
    googleurl = 'https://www.google.com/search?q={}&num={}&hl={}'.format(urllib.parse.quote('風起'), 100,'zh-TW')
    print(googleurl)
    driver.get(googleurl)

    while True:
        try:
            elmts = driver.find_elements(By.XPATH, "//div[@class='yuRUbf']/a")
            print('尋找')
            break
        except:
            pass
    print('搜尋結果數量',len(elmts))
    n = 0
    n_run = 0
    if len(elmts) == 0:
        n+=1
        print('異常次數',n)
        os.system('python3 reboot.py')
    else:
        print('正常')
    n_run+=1
    print('執行次數:',n_run)

def run_once(pport):
    global driver
    s = Service('/root/driver/chromedriver')
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125"
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--remote-debugging-port=9222')
    options.add_experimental_option("debuggerAddress", f"127.0.0.1:{pport}")
    options.add_argument("--user-agent=" + user_agent)
    options.add_argument("--incognito")
    
    driver = webdriver.Chrome(options=options, service=s)
    
    driver.delete_all_cookies()
    driver.set_window_size(1400, 1000)
    
    process_one()
    time.sleep(3)
    driver.quit()
   
try:
    os.system('docker container restart tiny10')
    time.sleep(1)
    run_once(9929)

except:
    os.system('docker container restart tiny9')
    time.sleep(15)