账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    新手python+webdriver+selenium使用unittest单元测试框架,无法正常switch_to.window
    48
    0

    最近在学习unittest单元测试框架,之前调试好的测试脚本,发现放在这个框架中,无法正常switch_to.window,总是报错无法定位到元素,个人感觉是因为窗口梅正常切换过去,新人求指教,谢谢,代码如下:

    main.py

    import time
    import unittest
    import auto_test
    suite = unittest.TestSuite()
    suite.addTest(auto_test.Python_autotest('get_browser'))
    suite.addTest(auto_test.Python_autotest('search'))
    suite.addTest(auto_test.Python_autotest('user_login'))
    suite.addTest(auto_test.Python_autotest('user_logout'))
    if __name__ == '__main__':
        runner = unittest.TextTestRunner()
        runner.run(suite)

    auto_test.py

    from selenium import webdriver
    import time
    import unittest
    class Python_autotest(unittest.TestCase):
        def setUp(self,driver = webdriver.Firefox()):
            print('Test is start')
            self.driver = driver
        def get_browser(self):
            self.driver.get("https://www.baidu.com/")
        def search(self):
            try:
                self.driver.find_element_by_xpath('//*[@id="kw"]').send_keys('segmentfault')
                self.driver.find_element_by_xpath('//*[@id="su"]').click()
            except Exception:
                print('No found everything, sorry!')
            else:
                time.sleep(1)
                self.driver.find_element_by_xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div[1]/h3/a").click()
        def user_login(self):
            self.driver.switch_to.window(self.driver.window_handles[-1])
            time.sleep(3)
            self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[1]/div[2]/a[1]').click()#点击页面中的前端菜单栏
        def user_logout(self):
            self.driver.quit()
        def tearDown(self):
            print('Test is finish')
    if __name__ == '__main__':
        unittest.main()
            
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 尐の潴猪 普通会员 1楼

      在使用unittest框架进行单元测试时,当使用selenium的switch_to.window方法时,可能会遇到无法正常切换到window的情况。这可能是由于浏览器的默认行为,或者是因为selenium版本的问题。

      以下是一些可能的解决方案:

      1. 检查selenium的版本:确保你正在使用的是selenium的最新版本。你可以通过运行以下命令来检查版本:

      selenium --version

      如果版本过低,你需要升级selenium。

      1. 检查浏览器的默认行为:许多浏览器在进行页面切换时会有一些默认的行为,比如阻止JavaScript和CSS的更新。你可以检查浏览器的控制台,看看是否有一些警告或错误。

      2. 检查浏览器的标签页设置:一些浏览器可能会阻止切换到非当前标签页。你可以尝试关闭并重新打开浏览器,看看是否能正常切换到其他标签页。

      3. 更新selenium的驱动:如果上述方法都无法解决问题,你可能需要更新selenium的驱动。你可以在selenium的官方网站上找到最新的驱动。

      希望这些信息对你有所帮助。如果你仍然遇到问题,欢迎继续提问。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部