gpt4 book ai didi

python - 带 Selenium 网络驱动程序的鼠标滚轮,在没有滚动条的元素上?

转载 作者:太空狗 更新时间:2023-10-29 18:27:12 51 4
gpt4 key购买 nike

我正在尝试驱动类似于 Google map 的网络 map 的一部分,在其中放大/缩小是通过在鼠标悬停时滚动来完成的。理想情况下,我希望能够做这样的事情:

someElement.scroll(-50)

我在文档中看到的最接近的方法是 clicksend_keys,但它们都不会滚动。我还尝试通过 Javascript 将卷轴发送到页面,例如driver.execute_script("scroll(0,-50)") 这似乎什么也没做。

我该怎么做?

最佳答案

要重现/测试鼠标滚轮,您必须向顶部元素发出 mouseovermousemovewheel 事件脚本注入(inject)。

这是一个 Google map 的工作示例:

from selenium import webdriver
from selenium.common.exceptions import WebDriverException

def wheel_element(element, deltaY = 120, offsetX = 0, offsetY = 0):
error = element._parent.execute_script("""
var element = arguments[0];
var deltaY = arguments[1];
var box = element.getBoundingClientRect();
var clientX = box.left + (arguments[2] || box.width / 2);
var clientY = box.top + (arguments[3] || box.height / 2);
var target = element.ownerDocument.elementFromPoint(clientX, clientY);

for (var e = target; e; e = e.parentElement) {
if (e === element) {
target.dispatchEvent(new MouseEvent('mouseover', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));
target.dispatchEvent(new MouseEvent('mousemove', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));
target.dispatchEvent(new WheelEvent('wheel', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY, deltaY: deltaY}));
return;
}
}
return "Element is not interactable";
""", element, deltaY, offsetX, offsetY)
if error:
raise WebDriverException(error)

options = webdriver.ChromeOptions()
options.add_argument("--disable-infobars --disable-extensions --window-size=1366,768")
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.google.co.uk/maps")

# get element
elm = driver.find_element_by_css_selector("#scene > div.widget-scene > canvas")

# zoom in with mouse wheel
wheel_element(elm, -120)

# zoom out with mouse wheel
wheel_element(elm, 120)

作为替代方案,您可以发送带有 Google map 的 +/- 缩放快捷方式:

# get element
elm = driver.find_element_by_css_selector("#scene > div.widget-scene > canvas")

# zoom in with shortcut
elm.send_keys("+")

# zoom out with shortcut
elm.send_keys("-")

关于python - 带 Selenium 网络驱动程序的鼠标滚轮,在没有滚动条的元素上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47274852/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com