📜  使用Selenium Python编写测试

📅  最后修改于: 2022-05-13 01:55:11.610000             🧑  作者: Mango

使用Selenium Python编写测试

Selenium 的Python模块是为使用Python执行自动化测试而构建的。 Selenium Python绑定提供了一个简单的 API 来使用Selenium WebDriver 编写功能/验收测试。通过Selenium Python API,您可以直观地访问Selenium WebDriver 的所有功能。本文说明了如何使用Selenium Python使用Python Selenium编写自动化测试。
如果您尚未安装Selenium及其组件,请从此处安装它们 - Selenium Python介绍和安装。 selenium包本身不提供测试工具/框架。可以使用 Python 的 unittest 模块编写测试用例。工具/框架的其他选项是 py.test 和 nose。

如何在Python中使用Selenium编写测试

我们使用Python的 unittest 框架来编写测试。让我们使用Python selenium测试在Python .org 上测试搜索功能。要了解有关 unittest 的更多信息,请访问 – unittest 文档。每行的解释都在代码中给出。
代码 -

Python3
# import all required frameworks
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
 
# inherit TestCase Class and create a new test class
class PythonOrgSearch(unittest.TestCase):
 
    # initialization of webdriver
    def setUp(self):
        self.driver = webdriver.Firefox()
 
    # Test case method. It should always start with test_
    def test_search_in_python_org(self):
         
        # get driver
        driver = self.driver
        # get python.org using selenium
        driver.get("http://www.python.org")
 
        # assertion to confirm if title has python keyword in it
        self.assertIn("Python", driver.title)
 
        # locate element using name
        elem = driver.find_element_by_name("q")
 
        # send data
        elem.send_keys("pycon")
 
        # receive data
        elem.send_keys(Keys.RETURN)
        assert "No results found." not in driver.page_source
 
    # cleanup method called after every test performed
    def tearDown(self):
        self.driver.close()
 
# execute the script
if __name__ == "__main__":
    unittest.main()


输出 -

使用 pytohn-selenium 编写测试