Re: [問題] Selenium如何釋放資源

看板Python作者 (霹靂狗)時間2年前 (2021/07/28 22:26), 2年前編輯推噓3(3011)
留言14則, 2人參與, 2年前最新討論串2/2 (看更多)
請問有關atexit.register這個功能是不是一執行python就立即觸發預載了? 因為Ctrl+C都還沒送chrome視窗就被關閉了 這個問題要怎麼解呢? 謝謝 =================================================================== 7/29修正 只要加了下文紅字區段,下Ctrr+C呼叫driver.quit()就會無效 import sys import atexit from selenium import webdriver def cleanup_function(): driver.quit() sys.exit(0) atexit.register(cleanup_function) url="http://google.com" options = webdriver.ChromeOptions() options.add_experimental_option('excludeSwitches', ['enable-logging']) driver = webdriver.Chrome(options=options) driver.get(url) input("") =================================================================== 7/31更新 用此方法成功 import sys import os import atexit import psutil from selenium import webdriver def cleanup_function(): for child in parray: killpid="taskkill /f /pid "+('{}'.format(child.pid)) os.system(killpid) sys.exit(0) atexit.register(cleanup_function) url="http://google.com" options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["enable-logging"]) driver = webdriver.Chrome(options=options) driver.get(url) p = psutil.Process(driver.service.process.pid) parray=p.children(recursive=True) input("") -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.104.34.155 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1627482385.A.FB9.html

07/29 00:16, 2年前 , 1F
win32api.SetConsoleCtrlHandler也是一樣狀況
07/29 00:16, 1F
※ 編輯: piligo (106.104.34.155 臺灣), 07/29/2021 09:55:41

07/29 10:19, 2年前 , 2F
https://bit.ly/2TFgnI7 我試過沒問題?
07/29 10:19, 2F

07/29 13:10, 2年前 , 3F
試了老半天 原來是這兩行在作怪 我有標紅字那段
07/29 13:10, 3F
※ 編輯: piligo (106.104.34.155 臺灣), 07/29/2021 13:11:47

07/29 13:12, 2年前 , 4F
當我把紅字清空就不影響atexit的動作 這是什麼狀況呢
07/29 13:12, 4F
※ 編輯: piligo (106.104.34.155 臺灣), 07/29/2021 13:20:13

07/29 13:23, 2年前 , 5F
clearup_function要傳入你當下的driver吧?
07/29 13:23, 5F

07/29 13:24, 2年前 , 6F
我不太確定是不是因為你用global driver造成
07/29 13:24, 6F

07/29 13:24, 2年前 , 7F
我也測過紅字沒問題
07/29 13:24, 7F

07/29 13:30, 2年前 , 8F
我把driver改名字了沒效 紅字沒問題但ctrl+c不會關閉網頁
07/29 13:30, 8F

07/29 13:31, 2年前 , 9F
我加紅字是為了讓DevTools listening on不會出現 還是有
07/29 13:31, 9F

07/29 13:31, 2年前 , 10F
其他方式可以不顯示DevTools listening on
07/29 13:31, 10F

07/29 14:39, 2年前 , 11F
是說有這麼複雜嗎不能用try finally driver.quit()?
07/29 14:39, 11F

07/29 23:21, 2年前 , 12F
我試了try還是無效 只要搭配紅字ctrl+c呼叫driver.quit()
07/29 23:21, 12F

07/29 23:22, 2年前 , 13F
就沒反應 紅字一拿掉就正常
07/29 23:22, 13F

07/30 23:34, 2年前 , 14F
最後靠psutil+atexit呼叫taskkill來達成
07/30 23:34, 14F
※ 編輯: piligo (106.104.34.155 臺灣), 07/31/2021 00:12:43
文章代碼(AID): #1X0MaH-v (Python)
文章代碼(AID): #1X0MaH-v (Python)