我同意alecxe你一般應該自動化整個過程。但是,在某些情況下,您可能正在編寫「一次性代碼」或概念驗證,因爲手動控制部分流程可能會有所幫助。如果我發現自己在這種情況下,我會做這樣的事情:
import time
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://google.com/')
try:
while True:
# This will fail when the browser is closed.
browser.execute_script("")
time.sleep(0.2)
# Setting such a wide exception handler is generally not advisable but
# I'm not convinced there is a definite set of exceptions that
# Selenium will stick to if it cannot contact the browser. And I'm not
# convinced the set cannot change from release to release.
except:
has_quit = False
while not has_quit:
try:
# This is to allow Selenium to run cleanup code.
browser.quit()
has_quit = True
except: # See comment above regarding such wide handlers...
pass
# Continue with the script...
print "Whatever"
到browser.quit()
的調用是使硒能清除後本身。這對於Firefox尤其重要,因爲Selenium會在一段時間內創建一堆臨時文件,其中可以將填充爲/tmp
(在Unix類型的系統上,我不知道Selenium將文件放在Windows系統上的哪個文件)。從理論上講,Selenium應該能夠正確處理在調用browser.quit()
時瀏覽器不再存在的情況,但我發現沒有捕獲到內部異常並且browser.quit()
會立即失敗的情況。 (順便說一下,這支持了我對Selenium在瀏覽器死機時可能引發的一系列異常的評論:即使Selenium也不知道Selenium可以提出什麼異常,這就是爲什麼browser.quit()
有時會失敗。)重複調用直到它成功似乎工作。
請注意,關閉瀏覽器後,browser
會變得無法使用。如果你想做更多瀏覽器的事情,你必須產生一個新的瀏覽器。
此外,通常不可能區分關閉瀏覽器的用戶和瀏覽器崩潰。
一般來說,在selenium瀏覽器窗口中混合自動和手動控制並不是一個好主意。我會自動執行這些「登錄」和「從服務器下載少量文件」部分。 – alecxe
可以請你給我一個登錄到https url鏈接的示例腳本,並下載具體的文件,我試過但沒有運氣,最後結束了這個,工作腳本將會有很大的幫助。謝謝:) @alecxe –