在實際項目中,會經常出現元素不在當前屏幕,需要滑動滾動條,才能顯示想要的元素。
這樣,如何通過定位滾動條,來定位到想要的元素呢,
webdriver不能直接定位到瀏覽器滾動條,只能通過execute_script()來執行js腳本,達到滾動條的目的
我們今天運用 window.scrollTo()的方法來定位
語法:scrollTo(xpos,ypos)
>>> xpos :橫座標
ypos:縱座標
直接上代碼:
# -*- coding: utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-5-21
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
#啓動瀏覽器
#driver = webdriver.Firefox()
driver = webdriver.Chrome()
url = "http://www.baidu.com"
driver.get(url)
#搜索selenium
driver.find_element(By.ID,"kw").send_keys("selenium")
driver.find_element(By.ID,"su").click()
time.sleep(3)
#調用js代碼拖動滾動條
driver.execute_script("window.scrollTo(0,1680)")
#直接拖動到最底部
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
#直接拖到頂部
driver.execute_script("window.scrollTo(0,0)")
time.sleep(3)
#退出瀏覽器
driver.quit()
>>>還有一種寫法:
js = "var q=document.body.scrollTop=0"
driver.execute_script(js)