【问题标题】:Calling functions from another file with Python/Selenium使用 Python/Selenium 从另一个文件调用函数
【发布时间】:2015-09-01 21:54:39
【问题描述】:

我在运行 selenium 测试并尝试从同一目录中的另一个文件调用函数时遇到问题。我浏览了很多关于导入模块的主题,但我没有运气。当我运行 test.py 时,它将在 wait_until_id_is_clickable 处停止,并引发 base.py 中的 NoSuchElementException。如果我把它放在 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

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.")

我正在使用nosetests 运行我的测试。任何帮助表示赞赏!

【问题讨论】:

    标签: python file selenium import


    【解决方案1】:

    base.py 中,您创建了一个无关的浏览器实例。删除这一行:

    browser = webdriver.Firefox()
    

    并将您在test.py 创建的浏览器传递给wait_until_id_is_clickable。修改定义为:

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

    并调用它:

    base.wait_until_id_is_clickable(browser, "community")
    

    【讨论】:

    • 哇哦。犯了这个错误我真的很傻。非常感谢!
    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2017-11-04
    • 2013-12-17
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多