使用Selenium+Python调用move_to_element传定位器报move_to requires a WebElement错误
问题根因
ActionChains.move_to_element() 方法要求传入的参数是已经定位完成的WebElement实例,你当前代码中直接传入了(By.XXX, 定位表达式)格式的定位器元组,类型不匹配触发了该报错。
你在unittest框架中可正常运行,大概率是unittest环境对应的BasePage的do_scroll方法内自带了定位元素的逻辑,迁移到pytest环境时漏了这步实现。
修复方案
修改BasePage类中的do_scroll方法,先通过定位器查找到实际WebElement后再传入ActionChains即可,建议增加显式等待避免元素未加载导致的后续报错:
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 self.wait = WebDriverWait(self.driver, 10) # 全局设置10秒显式等待超时 def do_scroll(self, by_locator): # 先等待元素可见,拿到WebElement实例 target_element = self.wait.until(EC.visibility_of_element_located(by_locator)) ac = ActionChains(self.driver) ac.move_to_element(target_element) ac.perform()
可选优化方案
如果你的场景没有特殊交互要求,也可以用JS原生滚动方法实现,兼容性更强,不依赖元素的可交互状态:
def do_scroll(self, by_locator): target_element = self.wait.until(EC.visibility_of_element_located(by_locator)) # 参数说明:behavior设置滚动动画,block设置元素滚动到视窗垂直居中位置 self.driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", target_element)
内容的提问来源于stack exchange,提问作者Naveed Ahmad
相关产品推荐
相关产品推荐

