selenium 切換標籤頁解決 get 超時問題

2021-10-23 22:55:31 字數 2982 閱讀 7648

從 gif 直觀地感受一下效果

我有大量 url 需要訪問,但是有些 url 會超時

為了避免超時,設定driver.set_page_load_timeout(3)限時3秒,一旦超時就會產生 timeoutexception

而且超時後標籤頁就卡柱了,只能通過driver.close()關閉

如果你只有乙個標籤頁,關閉就直接退出了,還得重啟

自然想到先保留乙個備用的標籤,原標籤超時需要關閉的時候就切換過來,然後再關閉,並開啟新標籤,保證任何時候都有兩個標籤頁可用!!

def

visit

(urls, timeout=3)

: driver.implicitly_wait(timeout)

# 操作、獲取元素時的隱式等待時間

driver.set_page_load_timeout(timeout)

# 頁面載入超時等待時間

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(

)# 關閉卡住的標籤

driver.switch_to.window(win)

# 切換到備用標籤

main_win = win # 切換到備用標籤

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

defun_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 =

''iflen

(version)

>0:

url =

'_'+version

version = requests.get(url)

.content.decode(

'utf8'

) driver_file =

''+ 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(

)

selenium 之切換標籤頁

1 獲取所有標籤頁 window handles driver.window handles print window handles window handles 切換最後乙個標籤頁 driver.switch to.window window handles 1 current url driv...

tab標籤頁切換

第一種 first second tab title li click function script 第二種 notice notice tit notice tit ul notice tit ul li notice tit ul a notice tit ul select 我是內容1 我是...

標籤頁的切換方式解析

標籤頁的切換方式 1 控制tab的顯示與隱藏 2 tab不切換,資料載入 控制tab的顯示與隱藏 前端指令碼 1 jquery實現 function 引入jquery檔案,簡潔 jquery檔案較大,瀏覽器不相容 2 js 實現 function selecttab showcontent,self...