我正在用 Python 构建 Selenium Webdriver 脚本。我的问题是,我正在执行一些操作,包括移动到某个位置并单击那里。我的操作不起作用,所以我想以非无头方式运行脚本来看看发生了什么,但是,由于光标没有出现在屏幕上,我无法看到鼠标是否按照我的预期移动。在浏览器窗口中运行 Selenium 时,有什么方法可以看到光标吗?我正在使用 Chromium,但我计划向此脚本添加更多浏览器,因此我需要至少适用于 Chromium 的东西,但如果有一个适用于其他浏览器的解决方案也会很有用。我必须移动到该元素并单击它的代码是这样的:
def scrollToCenter(driver, element):
# Get the height of the window
window_height = driver.execute_script("return window.innerHeight;")
# Get the position of the element relative to the top of the page
element_position = element.location['y']
# Calculate the position to scroll to
scroll_position = element_position - window_height/2
# Scroll the page to the desired position
driver.execute_script("window.scrollTo(0, {});".format(scroll_position))
# move the cursor to the element
actions = ActionChains(driver)
actions.move_to_element(element).perform()
def simulateClick(driver, el):
# Scroll to the point where the element is located
driver.execute_script("arguments[0].scrollIntoView();", el)
try:
# Move to the element and click it
scrollToCenter(driver, el)
el.click()
except Exception as e:
print(e)
查看正在执行的滚动也很有用。
另外,我想知道是否可以将这个测试用例的无头执行存储在视频中,这样我就不需要在检查鼠标是否处于正确位置时观看执行情况。
您正在寻找的部分答案可以在这里找到:https://stackoverflow.com/a/68556892/7058266(右键单击会使上下文菜单出现在光标单击的位置)。
但是,如果您遇到与在 Chrome 默认无头模式下无法正常点击相关的问题,那么您应该尝试较新的 Chrome 无头模式,该模式的功能与常规 Chrome 完全相同。详细信息在这里:https://stackoverflow.com/a/73840130/7058266
如果您想在无头模式下运行时查看屏幕,那么您应该查看 Chrome 的远程调试功能。详细信息在这里:从另一台机器进行 Chrome 远程调试
您可以尝试记录点击坐标,而不是显示光标。只需在操作之前运行此脚本,然后在控制台中查看
document.addEventListener("mousedown", (e) => console.log(e));