首页 > 解决方案 > ActionChains Selenium Python 无法正常工作

问题描述

我是使用 Python 的 Selenium 新手,我对 ActionChains 有问题,我无法理解。我想点击一个元素并将其移动到另一个元素 ActionChain ,我尝试了两种方法来做到这一点。

首先是 2 个 py 文件的组合,它们不起作用

import time
from selenium.webdriver.common.action_chains import ActionChains

def action_function(driver,start,des):
    time.sleep(2)
    ActionChains(driver).click_and_hold(start).move_to_element(des).release().perform()
    time.sleep(3)
import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from hilffunktionen import hilffunktion

class PythonOrgSearch(unittest.TestCase):


    driver = webdriver.Firefox('./geckodriver') 

    @classmethod
    def firsttest(self):
        self.driver.get('file:///C:/My-Project/Probe/index.html')

        time.sleep(5) # Let the user actually see something!
        dragitem = self.driver.find_element_by_id('mydivheader')
        print(dragitem.get_attribute('innerHTML'))
        time.sleep(5)
        destination = self.driver.find_element_by_id('destination')
        time.sleep(4)
        hilffunktion.action_function(self.driver,dragitem,destination)
        time.sleep(3)

但是如果我尝试在课堂上直接写它,它就可以了

import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

class PythonOrgSearch(unittest.TestCase):


    driver = webdriver.Firefox('./geckodriver') 
    driver.get('file:///C:/My-Project/Probe/index.html')

    time.sleep(5) # Let the user actually see something!
    dragitem = driver.find_element_by_id('mydivheader')
    print(dragitem.get_attribute('innerHTML'))
    time.sleep(5)
    destination = driver.find_element_by_id('destination')
    time.sleep(4)
    ActionChains(driver).click_and_hold(dragitem).move_to_element(destination).release().perform()
    time.sleep(3)

有人可以解释一下为什么吗?, 如果我只想用第一种方式写它,我该怎么做才能让它工作?. 我会非常感谢你的帮助

标签: pythonseleniumfrontend

解决方案


第二种方式“有效”,因为

A class definition is an executable statement. 

(在类定义中查看更多信息)

基本上python运行类定义中的语句。

如果你想做第一种方式(假设你想使用unittest),也许你可以将firsttest方法定义为test_xyz(self):......最后你可以调用unittest.main(),类似的基本示例


推荐阅读