一、基本知识:
滚动步骤: 1.通过selenium的查找元素的方法先找到元素; 2.通过执行js语句,将元素滚动到可见区域中; #找到元素: target = driver.find_element_by_xpath('//a[text()="hello"]') #将元素滚动到可见区域 driver。execute_script("arguments[0].scrollIntoView();",target) 1.移动到元素element对象的“底端”与当前窗口的“底部”对齐; driver.execute_script("arguments[0].scrollIntoView(false);",element) 2.移动到元素element对象的“顶端”与当前窗口的“顶部”对齐; driver.execute_script("arguments[0].scrollIntoView();",element) driver.execute_script("arguments[0].scrollIntoView(true);",element) 3.移动端页面底部 driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") 4.移动到页面顶部 driver.execute_script("window.scrollTo(document.body.scrollHeight,document.body.scrollHeight)")
二、案例代码:
from time import sleep 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 # 打开一个浏览器 driver = webdriver.Chrome() #调整为最大窗口: driver.maximize_window() #打开一个窗口 driver.get("https://www.baidu.com/") driver.find_element(By.ID,"kw").send_keys("陈然") #点击搜索 driver.find_element(By.ID,"su").click() ele='//span[text()="陈然 - 百度百科"]' param = (By.XPATH,ele) #显性等待 WebDriverWait(driver,10).until(EC.presence_of_element_located(param)) #滚动操作-先找到元素 # ele1=driver.find_element(By.XPATH,'//a[text()="(作家) 简历 - 名人简历"]') # sleep(3) #执行js语句,滚动画面 driver.execute_script("arguments[0].scrollIntoView();",ele1) # driver.execute_script("arguments[0].scrollIntoView(true);",ele1) # driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") # driver.execute_script("window.scrollTo(document.body.scrollHeight,document.body.scrollHeight)") sleep(3) driver.quit()
标签:web,execute,滚动,script,scrollIntoView,driver,element,自动化,scrollHeight From: https://www.cnblogs.com/crdhm12040605/p/17224557.html