Python selenium get頁面很慢時,處理辦法
方法一:設置超時時間
driver.get("url")等到頁面全部加載渲染完成后才會執行后續的腳本。
在執行腳本時,driver.get("url") ,如果當前的url頁面內容較多加載特別慢,很費時間,但是我們需要操作的元素已經加載出來,可以將頁面加載停掉,不影響后面的腳本執行,解決辦法
設置頁面加載timeout,get操作: try get except 腳本window.stop(), 使用GeckoDriver上有效果,但是在ChromeDriver上還是會有問題,拋出異常timeout后續腳本不會繼續執行
from selenium import webdriver import re driver = webdriver.Firefox() #設定頁面加載timeout時長,需要的元素能加載出來就行 driver.set_page_load_timeout(20) driver.set_script_timeout(20) #try去get try: driver.get("http://tieba.baidu.com/p/5659969529?red_tag=w0852861182") except: print("加載頁面太慢,停止加載,繼續下一步操作") driver.execute_script("window.stop()") last_page_element = driver.find_element_by_css_selector("li.l_pager.pager_theme_4.pb_list_pager >a:nth-child(12)") #定位到元素尾頁元素 #獲取尾頁頁碼鏈接文本 text = last_page_element.get_attribute("href") all_page_num = re.search("\d+$",text).group() # 正則匹配到頁碼 print("當前貼吧貼子總頁數為:%s"%all_page_num)
方法二:修改加載策略pageLoadStrategy(推薦)
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.support.ui import WebDriverWait
desired_capabilities = DesiredCapabilities.CHROME # 修改頁面加載策略 desired_capabilities["pageLoadStrategy"] = "none" # 注釋這兩行會導致最后輸出結果的延遲,即等待頁面加載完成再輸出 driver = webdriver.Chrome('browsers/chromedriver.exe') wait = WebDriverWait(driver, 10) #后面可以使用wait對特定元素進行等待 driver.get('http://qzone.qq.com/') # some code to work. print("Reach end.")
將頁面加載策略修改為none之后,頁面即使在加載過程中,程序也可以繼續執行。代碼中的pageLoadStrategy屬性可以設置為以下三種屬性:
normal:即正常情況下,selenium會等待整個界面加載完成(指對html和子資源的下載與解析,不包括ajax)
eager:要等待整個dom樹加載完成,即DOMContentLoaded這個事件完成,僅對html的內容進行下載解析
none:當html下載完成之后,不等待解析完成,selenium會直接返回
上面的代碼用了最后一種解析方式——none,不作等待,直接返回,然后在后面的代碼中可以用explicit_wait或者implicit_wait等方式來對特定元素進行等待捕獲。
不建議使用eager模式,會導致browser沒有生成,返回異常;
使用none模式相當於生成了dom,但不加載其它文件(圖片等)。