您好,登錄后才能下訂單哦!
這篇文章運(yùn)用簡(jiǎn)單易懂的例子給大家介紹使用selenium切換標(biāo)簽頁如何get超時(shí),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
從 gif 直觀地感受一下效果
我有大量 url 需要訪問,但是有些 url 會(huì)超時(shí)
為了避免超時(shí),設(shè)置driver.set_page_load_timeout(3)
限時(shí)3秒,一旦超時(shí)就會(huì)產(chǎn)生 TimeoutException
而且超時(shí)后標(biāo)簽頁就卡柱了,只能通過 driver.close()
關(guān)閉
如果你只有一個(gè)標(biāo)簽頁,關(guān)閉就直接退出了,還得重啟
自然想到先保留一個(gè)備用的標(biāo)簽,原標(biāo)簽超時(shí)需要關(guān)閉的時(shí)候就切換過來,然后再關(guān)閉,并打開新標(biāo)簽,保證任何時(shí)候都有兩個(gè)標(biāo)簽頁可用??!
def visit(urls, timeout=3): driver.implicitly_wait(timeout) # 操作、獲取元素時(shí)的隱式等待時(shí)間 driver.set_page_load_timeout(timeout) # 頁面加載超時(shí)等待時(shí)間 main_win = driver.current_window_handle for url in urls: all_win = driver.window_handles try: if len(all_win) == 1: driver.execute_script('window.open();') driver.get(url) # 頁面處理 pass except Exception: for win in all_win: if main_win != win: driver.close() # 關(guān)閉卡住的標(biāo)簽 driver.switch_to.window(win) # 切換到備用標(biāo)簽 main_win = win # 切換到備用標(biāo)簽 break
完整代碼
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.chrome.options import Options import time import requests import zipfile import os def un_zip(file_name, to_dir='./'): """unzip zip file""" zip_file = zipfile.ZipFile(file_name) if os.path.isdir(to_dir): pass else: os.mkdir(to_dir) for names in zip_file.namelist(): zip_file.extract(names, to_dir) zip_file.close() def download_driver(to_dir='./', version=''): print('install chrome-driver first') url = 'http://npm.taobao.org/mirrors/chromedriver/LATEST_RELEASE' if len(version)>0: url = 'http://npm.taobao.org/mirrors/chromedriver/LATEST_RELEASE_'+version version = requests.get(url).content.decode('utf8') driver_file = 'http://npm.taobao.org/mirrors/chromedriver/' + version + '/chromedriver_win32.zip' r = requests.get(driver_file) download_zip = "chromedriver_win32.zip" with open(download_zip, "wb") as code: code.write(r.content) un_zip(download_zip, to_dir) os.remove(download_zip) try: driver = webdriver.Chrome() except Exception as e: download_driver(to_dir='./', version='76') driver = webdriver.Chrome() with open("url.txt", 'r') as file: urls = [ line.strip('\n') for line in file.readlines()] visit(urls) for i in driver.window_handles: driver.switch_to.window(i) driver.close()
關(guān)于使用selenium切換標(biāo)簽頁如何get超時(shí)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。