我在 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)
這是另一個類代碼:
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
uj5u.com熱心網友回復:
move_to_element(to_element)
move_to_element(to_element)將滑鼠移動到元素的中間。它被定義為:
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()傳遞給where,因為您正在傳遞一個by_locatoras:
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()
uj5u.com熱心網友回復:
這是我缺少的東西:在 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/370772.html
下一篇:使Selenium等待文本可用
