简体   繁体   English

使用Python / Selenium从另一个文件调用函数

[英]Calling functions from another file with Python/Selenium

I'm having trouble running a selenium test and trying to call a function from another file in the same directory. 我在运行硒测试并尝试从同一目录中的另一个文件调用函数时遇到麻烦。 I've looked through many topics on importing modules but I'm having no luck. 我浏览了许多有关导入模块的主题,但是我没有运气。 When I run test.py , it will stop at wait_until_id_is_clickable with the NoSuchElementException being raised which is in base.py . 当我运行test.py时 ,它将停止在wait_until_id_is_clickable上,并引发base.py中的NoSuchElementException。 This function is successful if I put it in test.py . 如果将其放在test.py中,则此函数成功。

test.py test.py

import unittest
import base
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action.chains import ActionChains


class Selenium_Test(unittest.TestCase):


    def setUp(self):
        self.browser = webdriver.Firefox()

    def test_community_diversity(self):
        browser = self.browser
        browser.get("https://python.org")
        self.assertEqual(browser.title, "Welcome to Python.org")
        base.wait_until_id_is_clickable("community") #Function in base.py

        elem = browser.find_element_by_id("community")

        hover = ActionChains(browser).move_to_element(elem)
        hover.perform()
        browser.implicitly_wait(1)

        elem2 = elem.find_element_by_link_text("Diversity")
        self.assertEqual(elem2.is_displayed(), True)

    def tearDown(self):
        self.browser.close()

if __name__=="__main__":
    unittest.main()

base.py base.py

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()

def wait_until_id_is_clickable(element,time=10):
    wait = WebDriverWait(browser, time)
    try:
        wait.until(EC.element_to_be_clickable((By.ID,element)))
    except:
        raise NoSuchElementException("Could not find element in time.")

I am using nosetests to run my tests. 我正在使用鼻子测试进行测试。 Any help is appreciated! 任何帮助表示赞赏!

In base.py you create an extraneous browser instance. base.py您将创建一个无关的浏览器实例。 Remove this line: 删除此行:

browser = webdriver.Firefox()

and pass the browser you have created in test.py to wait_until_id_is_clickable . 并将您在test.py创建的浏览器传递给wait_until_id_is_clickable Modify the definition to: 将定义修改为:

def wait_until_id_is_clickable(browser, element, time=10):

and call it with: 并调用:

base.wait_until_id_is_clickable(browser, "community")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM