如何编写代码以在特定时间运行并在此之后退出?

时间:2018-08-10 07:53:48

标签: python python-3.x python-2.7 selenium-webdriver web-scraping

这是我的代码。我希望程序仅运行10秒钟,如果超过10秒钟,则程序应停止运行。为此,我使用了如图所示的while循环。但这是行不通的。请帮助我在同一代码中进行一些替代或增强。谢谢。

def second_func():
    first_id = driver.find_element_by_xpath('//*[@id="instant"]')
    first_id.click()

    ids = driver.find_element_by_xpath(
        '//*[@id="R629789109123908870"]/div[2]/table[1]/tbody/tr[11]/td[3]/a')
    ids.click()

    window_after = driver.window_handles[1]
    driver.switch_to.window(window_after)

    ans = driver.find_elements_by_xpath('//*[@id="P15_ENVIRONMENT_AAI_PASSWORD"]')
    for i in ans:
        current_password = i.text

    with open('data/password', 'r') as file:
        for line in file:
            previous_password = line

    if current_password == previous_password:
        # email_sender(current_password)
        print(current_password)

    else:
        with open('data/password', 'w') as file:
            file.write(current_password)
            file.close()
            print(current_password)
            # email_sender(current_password)

    driver.quit()

options = webdriver.ChromeOptions()
options.add_argument('--disable-extentions')
options.add_argument('--enable-popup-blocking')
options.add_argument('--start-maximized')

driver = webdriver.Chrome(executable_path='C:\\Users\\hp\\Downloads\\chromedriver',
                          chrome_options=options)


end_time = time.time() + 10
while time.time() < end_time:

    driver.get("http://demo.oracle.com")

    login = driver.find_element_by_xpath('//*[@id="sso_username"]')
    login.send_keys('username')

    password = driver.find_element_by_xpath('//*[@id="ssopassword"]')
    password.send_keys('password')

    login_click = driver.find_element_by_xpath(
        '/html/body/div/div[3]/div[1]/form/div[2]/span/input')
    login_click.click()

 else:
     driver.quit()

0 个答案:

没有答案