AttributeError: move_to requires a WebElement error calling move_to_element(by_locator) using Selenium and Python

AttributeError: move_to requires a WebElement error calling move_to_element(by_locator) using Selenium and Python

我在 pytest 中使用 ActionChains 滚动到一个元素,但出现错误“move_to 需要一个 WebElement”。我在 unittest 中使用了相同的代码,它运行良好,但在 pytest 中却没有。 这是我的代码:

import time
from selenium.webdriver.common.by import By
from Pages.BasePage import BasePage


class CreateGroup(BasePage):

     # ..........................Open created group Locators..............................
    GROUPS = (By.XPATH, "//span[text()='Groups']")
    SEARCH_GROUP = (By.XPATH, "//input[@ng-reflect-placeholder='Filter groups by name...']")
    GO_TO_GROUP = (By.XPATH, "//span[text()=' Go to Group ']")

    def __init__(self, driver):
        super().__init__(driver)

    def go_to_group(self, group):
        self.do_click(self.GROUPS)
        time.sleep(3)
        self.do_send_keys(self.SEARCH_GROUP, group)
        time.sleep(5)
        self.do_scroll(self.GO_TO_GROUP)

这是另一个 class 代码:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class BasePage:
    def __init__(self, driver):
        self.driver = driver

    def do_scroll(self, by_locator):
        ac = ActionChains(self.driver)
        ac.move_to_element(by_locator)
        ac.perform()

错误日志:

    def move_to(self, element, x=None, y=None):
        if not isinstance(element, WebElement):
>           raise AttributeError("move_to requires a WebElement")
E           AttributeError: move_to requires a WebElement

move_to_element(to_element)

move_to_element(to_element) moves the mouse to the middle of an element. It is defined 为:

def move_to_element(self, to_element):
    """
    Moving the mouse to the middle of an element.

    :Args:
     - to_element: The WebElement to move to.
    """

    self.w3c_actions.pointer_action.move_to(to_element)
    self.w3c_actions.key_action.pause()

    return self
    

因此,您需要将一个元素作为参数传递给 move_to_element(),而您将 by_locator 传递为:

ac.move_to_element(by_locator)

因此您会看到错误:

AttributeError: move_to requires a WebElement

解决方案

所以你的有效解决方案是:

def do_scroll(self, by_locator):
    element = WebDriverWait(self.driver, 20).until(EC.visibility_of_element_located(by_locator))
    ActionChains(self.driver).move_to_element(element).perform()

这是我遗漏的东西:在 do_scroll 函数中,我必须先获取元素,然后我需要继续处理该元素。

def do_scroll(self, by_locator):
    element = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located(by_locator))
    ac = ActionChains(self.driver)
    ac.move_to_element(element).perform()