nodriver 多分頁情況下,使用者手動關閉分頁造成 nodriver 無反應

目前 (2024-10-10) nodriver v0.37 還有一些神奇的缺點, 例如:同一個視窗下,開啟二個分頁,先把分頁1 存放在變數A,人工手動關閉分頁1之後,在程式碼存取變數A 就會讓程式掛掉,這裡的掛掉並不是 crash 或 raise exception, 而且類似 dead lock, main thread 走入一個不會跳出的無窮迴圈之中。

解法很簡單,因為出問題的是分頁(tab),所以只要存取根節點(driver) 就可以了。

範例:

async def nodriver_current_url(driver, tab):
is_quit_bot = False
exit_bot_error_strings = [
"server rejected WebSocket connection: HTTP 500",
"[Errno 61] Connect call failed ('127.0.0.1',",
"[WinError 1225] ",
]

url = ""
tab_count = len(driver.tabs)
#print("tab_count:", tab_count)

# PS: manually close tab will cause nodriver no response.
if tab_count > 1:
tab = driver.tabs[tab_count-1]

reset_active_tab = None
if not tab in driver.tabs:
print("tab closed by user before.")
tab = driver.tabs[tab_count-1]
reset_active_tab = tab

if tab:
url_dict = {}
try:
url_dict = await tab.js_dumps('window.location.href')
except Exception as exc:
print(exc)
str_exc = ""
try:
str_exc = str(exc)
except Exception as exc2:
pass
if len(str_exc) > 0:
for each_error_string in exit_bot_error_strings:
if each_error_string in str_exc:
#print('quit bot by error:', each_error_string, driver)
is_quit_bot = True

url_array = []
if url_dict:
for k in url_dict:
if k.isnumeric():
if "0" in url_dict[k]:
url_array.append(url_dict[k]["0"])
url = ''.join(url_array)
return url, is_quit_bot, reset_active_tab

url, is_quit_bot, reset_act_tab = await nodriver_current_url(driver, tab)
if not reset_act_tab is None:
tab = reset_act_tab

說明:tab變數是程式作用中的分頁(tab), 還到 tab變數不存在於 driver 之中時,設定最後一個分頁為作用中分頁。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *