selenium下拉滚动条的三种方法
一、设置滚动条位置
execute_script(“document.documentElement.scrollTop= 位置”)
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%86%AC%E5%A5%A5%E4%BC%9A&fenlei=256&rsv_pq=c61031d20000416d&rsv_t=34329gsBNwKJFQ%2Bmyc957YqRGPTtQjrdzsvJ%2Fpfwl4Dta6B4YxTZjnzxVE8&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=13&rsv_sug1=15&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&inputT=4248&rsv_sug4=4635')
time.sleep(3)
driver.execute_script("document.documentElement.scrollTop=10000")
time.sleep(1)
driver.quit()
二、js的window.scrollTo()方法
window.scrollTo(x,y) 通过坐标(x,y)进行滑动
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%86%AC%E5%A5%A5%E4%BC%9A&fenlei=256&rsv_pq=c61031d20000416d&rsv_t=34329gsBNwKJFQ%2Bmyc957YqRGPTtQjrdzsvJ%2Fpfwl4Dta6B4YxTZjnzxVE8&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=13&rsv_sug1=15&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&inputT=4248&rsv_sug4=4635')
time.sleep(3)
driver.execute_script("window.scrollTo(0,10000)")
time.sleep(1)
driver.quit()
三、定位元素进行滚动
execute_script(“arguments[0].scrollIntoView()”,element)
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
option = webdriver.ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=option)
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
'source': 'Object.defineProperty(navigator, "webdriver", {get:()=>undefined})'
})
driver.get('https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%86%AC%E5%A5%A5%E4%BC%9A&fenlei=256&rsv_pq=c61031d20000416d&rsv_t=34329gsBNwKJFQ%2Bmyc957YqRGPTtQjrdzsvJ%2Fpfwl4Dta6B4YxTZjnzxVE8&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=13&rsv_sug1=15&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&inputT=4248&rsv_sug4=4635')
driver.implicitly_wait(5)
target = driver.find_element(By.ID, '4')
driver.execute_script("arguments[0].scrollIntoView()", target)
time.sleep(3)
driver.quit()
这里需要用到上一节的反屏蔽 处理,否则不能正确定位到元素
|