
在Python 中使用Selenium Webdriver 捲動網頁
造訪包含動態載入內容的網頁(例如Facebook 好友清單)時,捲動通常會發生檢索所有可用資料所必需的。 Selenium Webdriver 提供了一系列在 Python 中啟用捲動的方法。
解決方案1:明確滾動定義的距離
要捲動到特定的垂直位置,請使用以下語法:
1 | driver.execute_script( "window.scrollTo(0, Y)" )
|
登入後複製
將Y 替換為所需的滾動高度,通常為1080 表示完整高清顯示器。
解決方案2:捲動到頁底
捲動到頁底:
1 | driver.execute_script( "window.scrollTo(0, document.body.scrollHeight);" )
|
登入後複製
解決方案3:無限加載滾動頁
對於Facebook等具有無限滾動功能的社交媒體平台:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | SCROLL_PAUSE_TIME = 0.5
# Get initial scroll height
last_height = driver.execute_script( "return document.body.scrollHeight" )
while True:
# Scroll down to bottom
driver.execute_script( "window.scrollTo(0, document.body.scrollHeight);" )
# Pause to allow loading
time.sleep(SCROLL_PAUSE_TIME)
# Check if scroll height has changed
new_height = driver.execute_script( "return document.body.scrollHeight" )
if new_height == last_height:
break
last_height = new_height
|
登入後複製
解決方案4:使用鍵盤快捷鍵
識別一個元素並應用以下內容:
1 | label.sendKeys(Keys.PAGE_DOWN)
|
登入後複製
以上是如何在 Python 中使用 Selenium WebDriver 滾動網頁?的詳細內容。更多資訊請關注PHP中文網其他相關文章!