from selenium import webdriver
from selenium.webdriver.chrome.options import Options


class searchinfo(object):
    def __init__(self):
        self.token1 = None

    def start(self,ip):
        self.token1=self.login(ip)
        return self.token1

    def login(self,ip):
        try:
            #return "test" + str(datetime.datetime.now())
            chrome_options = Options()
            chrome_options.add_argument("--headless")
            chrome_options.add_experimental_option("detach",True)
            chrome_options.add_argument("window-size=1920x1080")
            chrome_options.add_argument("--start-maximized")
            chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
            browser = webdriver.Chrome(
                executable_path=r'D:\flightinfo\Google\Chrome\Application\chromedriver.exe',
                options=chrome_options)
            browser.set_window_size(width=2000,height=300)
            browser.get("http://%s/"%ip)
            browser.find_element_by_id("username").send_keys("adminadmin")
            browser.find_element_by_id("password").send_keys("adminadmin")
            browser.find_element_by_id("logonButton").click()
            # print(browser.get_cookies())
            for cookie in browser.get_cookies():
                #print(str(browser.get_cookies()))
                if "keepOnLine" not in str(browser.get_cookies()):
                    browser.get("http://%s/" % ip)
                    browser.switch_to.frame("title_top")
                    browser.find_element_by_id("enableSessionTimeout").click()
                if "keepOnLine" in cookie.values() and cookie["value"] == "false":
                    browser.get("http://%s/" % ip)
                    browser.switch_to.frame("title_top")
                    browser.find_element_by_id("enableSessionTimeout").click()
            for cookie in browser.get_cookies():
                #print(str(browser.get_cookies()))
                if "auth" in cookie.values():
                    return "auth=" + cookie["value"] + ";CUR_LANG=cn;" + "CTCPgSz=10;" + "keepOnLine=true"
                else:
                    return "fail"
        except Exception:
            return "fail"

        #print(str(browser.get_cookies()))


if __name__ == '__main__':
    fl = searchinfo()


