13 - selenium 常見操作,js操作-將元素滾動到頁面可見區域


  我們在自動化測試中,會遇到需要把瀏覽器頁面的元素移動到可見區域,就需要使用頁面向上或者向下滾動

js操作-滾動條:使用: selenium 當中使用 execute_script   (譯:埃克斯Q特。思怪潑特) 方法 執行 js 語句;

 

頁面元素滾動到可見區域常用的操作:

arguments[0]:(譯:a哥門磁)外部 python 傳進來的變量也就是 element

scrollIntoView :(譯:死光兒。恩特外歐)

element:元素定位,找到元素

1、移動到元素element對象的“底端”與當前窗口的“底部”對齊:

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

2、移動到元素element對象的“頂端”與當前窗口的“頂部”對齊 :

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

3、移動到頁面底部:

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

4、移動到頁面頂部:

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

 

將元素滾動到可見區域 :百度查詢“電腦”,將“電腦_百度百科”移動到底部。

1、需要滾動的對象:先定位元素

2、js的滾動語句:上面的四種方法

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

driver.find_element_by_id("kw").send_keys("電腦", Keys.ENTER)
# driver.find_element_by_id("su").click()

# 1、找到我要滾動到可見區域的元素
loc = (By.XPATH, '//a[text()="_百度百科"]')
WebDriverWait(driver, 20).until(EC.visibility_of_element_located(loc))
element = driver.find_element(*loc)

# 2、執行js的函數將元素滾動到可見區域:execute_script(譯:埃克斯Q特。思怪潑特)
driver.execute_script("arguments[0].scrollIntoView(false);", element)  # 因頂部有遮罩層,所以與可見區域的底部對齊。

#
執行js的函數,如果是兩個參數 # driver.execute_script("arguments[0].scrollIntoView(false);alert(arguments[1])", element, "200") # 滾動到可見區域后,進行點擊操作 element.click() # 等待五秒,查看效果,關閉瀏覽器 time.sleep(5) driver.quit()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM