webdriver高级应用- 启动带有用户配置信息的firefox浏览器窗口

由于WebDriver启动FireFox浏览器时会启用全新的FireFox浏览器窗口,导致当前机器的FireFox浏览器已经配置的信息在测试中均无法生效,例如已经安装的浏览器插件、个人收藏夹等。为了解决此问题,自动化测试脚本中需要使用指定的配置信息来启动FireFox浏览器窗口。

1.生成用户自定义的FireFox浏览器配置文件:

在CMD中使用cd命令进入firefox.exe文件所在目录(比如:C:Program FilesMozilla Firefox),
并输入firefox.exe -ProfileManager -no-remote命令,然后按Enter键,
调出“Firefox – 选择用户配置文件”操作窗口


如果firefox.exe -ProfileManager -no-remote 执行弹出一个页面说找不到路径,解决方法:
在火狐的菜单“帮助”下,选择“故障排除信息”,点击后,在弹出的页面中找到“配置文件夹 ”的
选项,点击“打开文件夹”,可以获取默认配置文件的全路径。

2.python实现代码如下:

#encoding=utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import unittest, time

class TestFailCaptureScreen(unittest.TestCase):

    def setUp(self):
        # 创建存储自定义配置文件的路径变量
        #proPath = "C:\Users\wuxiaohua\AppData\Roaming\Mozilla\Firefox\Profiles\tbbmxtkv.webdriver"
        #proPath = "C:\Users\wuxiaohua\AppData\Roaming\Mozilla\Firefox\Profiles\g6m1cswj.default"
        proPath = "C:UsersAdministratorAppDataRoamingMozillaFirefoxProfilesffv3vcdx.default"
        #proPath = "C:\UsersAdministratorAppDataRoamingMozillaFirefoxProfilesw6k7fiwp.qwq1"
        # 加载自定义配置文件到FirefoxProfile实例中,
        # 等价profile = webdriver.FirefoxProfile(proPath)
        profile = webdriver.firefox.firefox_profile.FirefoxProfile(proPath)
        # 将添加了新配置文件的Firefox浏览器首页设为搜狗主页
        profile.set_preference("browser.startup.homepage", "http://www.sogou.com")
        # 设置开始页面不是空白页,0表示空白页,
        # 这一步必须做,否则设置的主页不会生效
        profile.set_preference("browser.startup.page", 1)
        # 启动带自定义配置文件的Firefox浏览器
        self.driver = webdriver.Firefox(executable_path="e:\geckodriver", firefox_profile=profile)

    def testSoGouSearch(self):
        # 等待5秒,以便浏览器启动完成
        time.sleep(5)
        try:
            # 找到搜狗主页搜索输入框页面元素
            searchBox = self.driver.find_element_by_id("query")
            # 在找到的搜索输入框中输入“光荣之路自动化测试”
            searchBox.send_keys(u"光荣之路自动化测试")
            # 找到搜索按钮,并点击
            self.driver.find_element_by_id("stb").click()
            time.sleep(10)
        except NoSuchElementException, e:
            print "修改带自定义配置文件的浏览器主页不成功!"

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
原文地址:https://www.cnblogs.com/qingqing-919/p/8716501.html