UI自动化测试(六) selenium调用js(滚动条,修改html参数)

利用selenium调用js

from selenium import webdriver

driver = webdriver.chrome()
driver.execute_script(js)  # js即为JS代码

滚动条:

js语法

    scrollIntoView();

python语法

    # 顶部对齐
    js = "arguments[0].scrollIntoView();"
    # 底部对齐
    js = "arguments[0].scrollIntoView(false);"  # arguments[0]的意思为下方传的除js外的第一个参数
    driver.execute_script(js, WebElement)  # js语法, 元素对象
    
    # 页面底部
    js = "window.scrollTo(0,document.body.scrollHeight)"
    # 页面顶部
    ks = "window.scrollTo(document.body.scrollHeight, 0)"
    driver.execute_script(js)

实例:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

driver.get("https://www.baidu.com/")
loc = (By.ID, "kw")
driver.find_element(*loc).send_keys("selenium")
driver.find_element(By.ID, "su").click()

js = "arguments[0].scrollIntoView(false);"  # 底部对齐元素对象
loc = (By.XPATH, "//div[text()='相关搜索']")
target = driver.find_element(*loc)
driver.execute_script(js, target)

js = "arguments[0].scrollIntoView();"  # 顶部对齐元素对象, 百度的搜索框为悬浮状态所以滚动时,实际目标会被挡住
loc = (By.XPATH, '//*[text()="搜索工具"]')
target = driver.find_element(*loc)
driver.execute_script(js, target)

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

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

你可能感兴趣的:(UI自动化测试(六) selenium调用js(滚动条,修改html参数))