相信大家在selenium爬取網頁的時候都遇到過這樣的問題:就是網頁內容需要用鼠標滾動加載剩余內容,而不是一次全部加載出網頁的全部內容,這個時候如果要模擬翻頁的時候就必須加載出全部的內容,不然定位元素會找不到,出現報錯。
這里提供兩種方法供大家參考
一,通過selenium模擬瀏覽器,然后設置瀏覽器高度足夠長,最后延時使之能夠將頁面的內容都能夠加載出來
- import time
- from selenium import webdriver
- driver = webdriver.Firefox()
- driver.set_window_size(1000,30000)
- driver.get(url)
- time.sleep(5)
二,通過selenium模擬瀏覽器下拉操作
- from selenium import webdriver
- import time
- browser.execute_script("window.scrollBy(0,3000)")
- time.sleep(1)
- browser.execute_script("window.scrollBy(0,5000)")
- time.sleep(1)
- browser.execute_script("window.scrollBy(0,8000)")
- time.sleep(1)
補充知識:針對懶加載如何實現selenium 滑動至頁面底部page_source一次性包含全部網頁內容
有時網站使用了懶加載技術:只有在瀏覽器中縱向滾動條滾動到指定的位置時,頁面的元素才會被動態加載。
注意,在加載之前,selenium的page_source是不會包含該頁面的內容,page_source只包含加載出來的頁面內容。
那么如何實現加載全部內容了,就需要模擬人滾動滾動條的行為,實現頁面的加載
- from selenium.webdriver.chrome.options import Options
- from selenium import webdriver
- from selenium.common.exceptions import TimeoutException
- from selenium.webdriver.support.wait import WebDriverWait
- from selenium.webdriver.common.by import By
- from selenium.webdriver.support import expected_conditions as EC
-
- def scroll_until_loaded(self):
- check_height = self.browser.execute_script("return document.body.scrollHeight;")
- while True:
- self.browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
- try:
- self.wait.until(lambda driver: self.browser.execute_script("return document.body.scrollHeight;") > check_height)
- check_height = self.browser.execute_script("return document.body.scrollHeight;")
- except TimeoutException:
- break
這里懶加載并不是一直有效, 當網速不好時,加載超過self.wait()時間, 頁面還沒加載出來時, 會認為全部加載完成, page_source里面的代碼就會是以前加載出來的, 所以執行翻頁操作后, 要執行time.sleep(3), 等待網頁加載, 更新html再獲取網頁源代碼
以上這篇淺談selenium如何應對網頁內容需要鼠標滾動加載的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持我們。