这是一个bug吗:Python的Selenium ActionChains,与“perform”函数之间的奇怪延迟?

2024-10-05 13:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写Selenium的WebDrivers函数,以类似于人类的方式单击页面中的坐标。它使用Firefox,但我也注意到ChromeDriver也存在同样的问题

它有两个参数:一个元素(我的函数从中获得坐标)和目标点。它将鼠标从一个点移动到另一个点,以模拟真实的人类。然后,它将单击目标点

奇怪的是,我发现“action.perform”函数的速度越慢,偏移量越大

此外,我还发现了一些可能是巧合的事情:它被卡住的时间大约是x的值,我从该值开始偏移元素。所以当我移动(x:0,y:0)时,它很快,但是当我在循环中移动偏移量(x:14,y:2)时,它会等待大约14秒。不过这可能只是巧合

最后,我听说actionchains在java中有一个*kwarg参数,其中包括一个延迟。我读到,大多数人没有使用它,这导致了默认的250毫秒的惩罚。但是我在python中找不到这样的东西

有没有人知道我可能做错了什么,或者这是一个bug

非常感谢你

这是我写的一个简化的例子,它再现了这个问题

import selenium.webdriver, re
from selenium.common.exceptions import NoSuchElementException  
from selenium.webdriver import ActionChains  
import numpy as np
from time import sleep as delay

def hanging_line(point1, point2): #calculates the coordinates for none-straight line which gets from point1 to point2
    a = (point2[1] - point1[1])/(np.cosh(point2[0]) - np.cosh(point1[0]))
    b = point1[1] - a*np.cosh(point1[0])
    x = np.linspace(point1[0], point2[0], 100)
    y = a*np.cosh(x) + b
    return (x,y)


def click(element,coordinates):
    delay(3)
    actionmouse = ActionChains(driver)
    actionmouse.move_to_element(element);
    actionmouse.perform();

    targetx = coordinates[0]
    targety = coordinates[1]

    points = hanging_line((0,0),(targetx,targety))

    for i in range(len(points[0])):
        x = int(round(points[0][i],1)) #I tried to round it, and to convert it to an int,
        y = int(round(points[1][i],1)) #but found no differences in performance

        print('moving')
        actionmouse.move_by_offset(x, y)
        print('performing') #get stuck here for seconds=`x` value
        actionmouse.perform()
        print(x,y)


    action = ActionChains(driver)
    action.move_to_element_with_offset(element, targetx, targety).click().perform()
    delay(0.3)


driver = selenium.webdriver.Firefox()
driver.get("https://www.dailychess.com/chess/chess-fen-viewer.php")
element = driver.find_element_by_class_name('sidebar-action-button')
click(element,[37,94])


Tags: tofromimportdriverseleniumnpactionelement

热门问题