Webdriver scroll bar operation

When the element to be operated is outside the visible area of ​​the page, it is necessary to scroll the element to be operated into the visible area.

step:

1. The element found first

element=driver.find_element_by_xxx("xxx")

 

2. Drag the element to the visible area and realize it through JavaScript statements, the following 4 scenarios

1) Move to the "top" of the element object to align with the "top" of the current window:

driver.execute_script("arguments[0].scrollIntoView();",element)

 

2) Move to the "bottom" of the element object to align with the "bottom" of the current window:

driver.execute_script("arguments[0].scrollIntoView(false);",element)

 

3) Move to the bottom of the page:

driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")

 

4) Move to the top of the page:

driver.execute_script("window.scrollTo(document.body.scrollHeight,0)")

 

from selenium import webdriver
import time
driver=webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get("https://ke.qq.com/")

#找到腾讯课堂,近30天最多人在学板块
element=driver.find_element_by_xpath("//div[@data-name='近30天最多人在学']//h2")

#移动元素element与当前窗口的“底部”对齐:
driver.execute_script("arguments[0].scrollIntoView(false);",element)

#移动元素element与当前窗口的“顶部”对齐:
time.sleep(2)
driver.execute_script("arguments[0].scrollIntoView();",element)

#滚动到页面最底部
time.sleep(2)#一定要等一下
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")

#然后滚动到页面最顶部
time.sleep(2)
driver.execute_script("window.scrollTo(document.body.scrollHeight,0)")

3. Re-operate elements

element.xxx()

 

 

 

Guess you like

Origin blog.csdn.net/weixin_42162451/article/details/86667850