當使用Selenium爬取一些頁面時,有些頁面加載速度特別慢,而我們又不需要等待頁面完全加載完畢。
此時可以通過driver.set_page_load_timeout()來設置頁面超時時間。
捕獲異常,並執行js腳本window.stop()即可實現,代碼如下。
from selenium import webdriver driver = webdriver.Chrome() driver.set_page_load_timeout(3) try: driver.get('https://hk.louisvuitton.com/zht-hk/homepage') print('finish load ....') except Exception: driver.execute_script('window.stop()') print(driver.title) finally: driver.quit()
