硒-X时间后刷新所有选项卡

时间:2018-10-24 14:09:08

标签: python selenium selenium-webdriver selenium-chromedriver

我有一个通过Selenium Webdriver创建的旋转破折号,我注意到页面需要每隔几个小时刷新一次。如何将其添加到代码中?

有8个选项卡打开,并且每10秒循环浏览每个选项卡。寻找一种每2-3小时刷新一次所有打开的标签页的方法。当前代码。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
usernameStr = 'USERNAME'
passwordStr = 'PASSWORD'

options = Options()
options.add_argument('--maximized')
options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\pc\Desktop\chromedriver.exe')
driver.get('https://Sign in link')
# fill in username and hit the next button
username = driver.find_element_by_id('username')
username.send_keys(usernameStr)
password = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'password')))
password.send_keys(passwordStr)
nextButton = driver.find_element_by_class_name('emp-submit')
nextButton.click()

#second tab
driver.execute_script("window.open('about:blank', 'tab2');")
driver.switch_to.window("tab2")
driver.get('https://link#2')

#third tab
driver.execute_script("window.open('about:blank', 'tab3');")
driver.switch_to.window("tab3")
driver.get('https://link#3')

#fourth tab
driver.execute_script("window.open('about:blank', 'tab4');")
driver.switch_to.window("tab4")
driver.get('https://link#4')

#fifth tab
driver.execute_script("window.open('about:blank', 'tab5');")
driver.switch_to.window("tab5")
driver.get('https://link#5')

#sixth tab
driver.execute_script("window.open('about:blank', 'tab6');")
driver.switch_to.window("tab6")
driver.get('https://link#6')

#seventh tab
driver.execute_script("window.open('about:blank', 'tab7');")
driver.switch_to.window("tab7")
driver.get('https://link#7')

#eigth tab
driver.execute_script("window.open('about:blank', 'tab8');")
driver.switch_to.window("tab8")
driver.get('https://link#8')

while True:
    Windows = driver.window_handles
    for window in Windows:
        driver.switch_to.window(window)
        time.sleep(10)

1 个答案:

答案 0 :(得分:2)

如果您需要在2小时后刷新所有标签,可以尝试

while True:
    time.sleep(7200)  # sleep for 2 hours
    Windows = driver.window_handles
    for window in Windows:
        driver.switch_to.window(window)
        driver.refresh()

如果您需要2到3个小时之间的随机时间,可以使用

from random import randint

time.sleep(7200 + randint(0, 3600))

代替time.sleep(7200)