【selenium】下拉滚动条


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')
# 等待3秒
time.sleep(3)
# 滚动到底部
driver.execute_script("document.documentElement.scrollTop=10000")
# 等待1秒
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')
# 等待3秒
time.sleep(3)
# 滚动到底部
driver.execute_script("window.scrollTo(0,10000)")
# 等待1秒
time.sleep(1)
# 退出所有页面
driver.quit()

三、定位元素进行滚动

execute_script(“arguments[0].scrollIntoView()”,element)

  • 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')
    # 等待3秒
    driver.implicitly_wait(5)
    # 定位到目标处
    target = driver.find_element(By.ID, '4')
    # 滚动到所定位的目标处
    driver.execute_script("arguments[0].scrollIntoView()", target)
    # 等待1秒
    time.sleep(3)
    # 退出所有页面
    driver.quit()

这里需要用到上一节的反屏蔽处理,否则不能正确定位到元素


Author: Polaris119
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Polaris119 !
评论
  TOC