模拟硒中的鼠标运动



我在硒中有小脚本来自动化一个网站。我还做了一些功能来模拟鼠标移动,以生成大量模仿人类行为的鼠标移动,而不是从一个选择器跳到另一个选择器。我在新线程中运行它,但在第一次迭代后,它会抛出 selenium.common.exceptions.MoveTargetOutOfBoundsException: 消息:将目标移出界外。

感谢:)的帮助

类脸书((:

def __init__(self, login, password, counter=0):
self.login = login
self.password = password
self.browser = webdriver.Chrome("D:seleniumchromedriver.exe")
self.browser.get("https://www.facebook.com/")
self.browser.set_window_size(1400,600)
self.action = ActionChains(self.browser)
self.thread()
def move_mouse(self):
actions = ActionChains(self.browser)
while True:
delay = random.uniform(0.1,0.3)
x = random.randint(400,900)
y = random.randint(100,400)
actions.move_by_offset(x,y).perform()
print("x:"+str(x)+" y:"+str(y))
time.sleep(2)
def thread(self):
newThread = threading.Thread(target=self.move_mouse, daemon=True)
newThread.start()

运行此代码,您最终将移动到最大 x,y 位置并尝试超越窗口边框。我做了一些研究,发现当元素是身体标签时,你可以用move_to_element_with_offset移动到特定位置。

这是我的概念证明:

def move_mouse_to_random_position(driver):
max_x, max_y = driver.execute_script("return [window.innerWidth, window.innerHeight];")
body = driver.find_element_by_tag_name("body")
actions = ActionChains(driver)
x = random.randint(0, max_x)
y = random.randint(0, max_y)
actions.move_to_element_with_offset(body, x, y)
actions.perform()

最新更新