我正在尝试驱动类似于Google Maps的网络地图的一部分,在该地图上,通过鼠标悬停时的滚动来进行放大/缩小。理想情况下,我希望能够执行以下操作:
someElement.scroll(-50)
我在文档中看到的最接近的方法是click和send_keys,但是这两个方法都不可以滚动。我也尝试通过Javascript将滚动条发送到页面,例如,driver.execute_script("scroll(0,-50)")这似乎没有任何作用。
click
send_keys
driver.execute_script("scroll(0,-50)")
我怎样才能做到这一点?
要重现/测试鼠标滚轮,您必须通过脚本注入将mouseover,mousemove和wheel事件发送到顶部元素。
mouseover
mousemove
wheel
这是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地图+/-的缩放比例:
# 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("-")