如何使用硒将网页滚动到目标元素 [英] How to Scroll web page to the target element using selenium

查看:90
本文介绍了如何使用硒将网页滚动到目标元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想滚动到硒元素,但我希望它位于页面顶部,而不仅仅是在页面上可见.

I want to scroll to an element in selenium, but I want it to be at the top of the page, not just visible on the page.

如何使页面滚动,以便滚动到的元素位于浏览器的顶部?

How can I make it so that the page scrolls such that the element being scrolled to is at the top of the browser?

target = browser.find_element_by_css_selector(".answers-wrap")
actions = ActionChains(browser)
actions.move_to_element(target)
actions.perform()

推荐答案

以下是我们使用此页面的示例

要将网页垂直滚动1000像素,请使用 execute_script("window.scrollBy(0,1000)")

示例

import time
from selenium import webdriver

chrome_browser = webdriver.Chrome()
chrome_browser.get('https://stackoverflow.com/questions/61071131/'
                   'scroll-in-selenium-driver-to-make-element-at-top-of-the-page')
time.sleep(4)
''' execute_script("window.scrollBy(x-pixels,y-pixels)")
    scroll down the page by  1000 pixel vertical
'''
chrome_browser.execute_script("window.scrollBy(0,1000)")

execute_script("window.scrollBy(x-pixels,y-pixels)")

execute_script("window.scrollBy(x-pixels,y-pixels)")

x-pixels是x轴上的数字,如果number为正数则向左移动,如果number为负数则向右移动.y-pixels是y轴上的数字. ,如果数字为正,则向下移动;如果数字为负,则向上移动.


将网页向下滚动到目标元素.

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

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

参数[0]"表示页面的第一个索引从0开始.

代码示例

import time
from selenium import webdriver

chrome_browser = webdriver.Chrome()
chrome_browser.get('https://stackoverflow.com/questions/61071131/'
                   'scroll-in-selenium-driver-to-make-element-at-top-of-the-page')
time.sleep(4)

element = chrome_browser.find_element_by_css_selector(
    "#footer > div > nav > div:nth-child(1) > h5 > a")

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

这篇关于如何使用硒将网页滚动到目标元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆