强制Selenium使用便携版Firefox应用程序

8 投票
2 回答
8431 浏览
提问于 2025-04-17 21:34

我在电脑上安装了Firefox 14,同时还有一个便携版的Firefox 25.0.1,用来测试一个网站。

由于我测试的网站有一些限制,我不能在安装的Firefox 14上运行我的测试。而且我也不能升级这个Firefox 14。

所以我想找个办法,使用这个便携版的Firefox,而不是安装的Firefox 14。

我该怎么让selenium使用这个便携版,而不是安装的版本呢?如果有人能给我推荐一些详细的文章或博客,那就太好了。

我的代码是这样的:

* 变量 *

${SELENIUM_HUB}     remote_url=http://127.0.0.1:4444/wd/hub
${BROWSER}      firefox D:\\Firefox Portable\\FirefoxPortable\\firefox.exe
${CLIENT_URL}       https://abcd.aline.local

Open Browser    ${CLIENT_URL}    ${BROWSER}   ${SELENIUM_HUB}

我试着把路径指定为D:/Firefox Portable/FirefoxPortable/firefox.exe,但这样不行,因为'/'会被去掉。有什么想法吗?

PS:我使用的编程语言是Python。

2 个回答

1

Selenium2Library这个工具不允许你在打开浏览器时指定浏览器的路径,但它有一个叫做remote_url的参数,这个参数可能会很有用。在Selenium2Library还没有很好支持PhantomJS之前,使用PhantomJS的方法就是通过这个remote_url,像这样http://spage.fi/phantomjs

所以理论上,我们应该可以先启动可移动版的Firefox,然后通过remote_url连接到它。大概是这样的。

Start Process    c:\\path\\to\\portable\\firefox.exe
Open Browser    http://google.com    firefox    main browser    http://localhost:${firefox webdriver port}

问题是我不知道Firefox默认使用哪个webdriver端口,或者怎么指定这个端口。此外,可能还需要安装webdriver.xpi这个Firefox的插件。这个插件可以在这里找到:C:\Python27\Lib\site-packages\selenium\webdriver\firefox,或者你Python安装的其他地方。

Selenium2Library里有一个Create Webdriver的功能,它允许我们指定firefox_binary(还有其他参数)。所以理论上

Create Webdriver    Firefox    firefox_binary=c:\\path\\to\\portable\\firefox.exe

应该可以工作,但我得到的错误是“AttributeError: 'str' object has no attribute 'launch_browser'”。

抱歉我没有找到解决办法,但如果你深入研究一下Firefox的webdriver端口或者Create Webdriver的具体工作原理,可能会有新的发现。

6

你可以通过FirefoxBinary这个类来指定你想要的Firefox浏览器的路径,然后把它作为firefox_binary参数传给你的Firefox webdriver。

http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_binary.html

还有

http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.webdriver.html#module-selenium.webdriver.firefox.webdriver

确保你指定的浏览器路径是正确的,可以用类似这样的代码:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

firefox_binary = FirefoxBinary("D:\\Firefox Portable\\FirefoxPortable\\firefox.exe")
driver = webdriver.Firefox(firefox_binary=firefox_binary)

如果你使用robotframework,可以试试这样的代码:

${firefox_binary}=  Evaluate    sys.modules['selenium.webdriver.firefox.firefox_binary'].FirefoxBinary("D:\\Firefox Portable\\FirefoxPortable\\firefox.exe")    sys, selenium.webdriver.firefox_binary
Create Webdriver    Firefox    firefox_binary=${firefox_binary}

这可能会有效。

撰写回答