17

I've spent the last few days messing around with Selenium, Tor, and Firefox as a combination for multiple tasks. I've managed to write a simple script in Python that takes control of Firefox through Selenium, while Firefox is connected to Tor for privacy.

Now, I'm looking for a way to save resources, so I thought of running Firefox in headless mode, which I thought was a common feature but it doesn't seem to be that. I'm looking for a method to do just that. The reason for it being Firefox and not some terminal based browser is because of the extension "TorButton" that I'm using within Firefox. It has javascript injections built in to it that help with privacy.

If anyone has done this before (which I'm sure many have!), some tips would be greatly appreciated, thank you!

4

5 回答 5

11

xvfb 是执行此操作的常用方法。搜索“selenium xvfb”应该会找到很多,例如:

于 2012-04-08T05:16:53.610 回答
10

自 2017 年 9 月 28 日版本 56 发布以来,Firefox 无头模式可在所有三个主要操作系统中使用。

您可以通过 设置无头模式webdriver.FirefoxOptions(),就像使用 Chrome 一样:

from selenium import webdriver

options = webdriver.FirefoxOptions()
options.add_argument('headless')
driver = webdriver.Firefox(options=options)

PS 如果您使用 Selenium < 3.8.0,则必须替换webdriver.FirefoxOptions()webdriver.firefox.options.Options()(请参阅 PR #5120)。

此外,使用环境变量MOZ_HEADLESS也会做同样的事情:

import os
from selenium import webdriver

os.environ['MOZ_HEADLESS'] = '1'  # <- this line
driver = webdriver.Firefox()
于 2017-11-25T01:14:34.543 回答
5

或者使用真正的无头浏览器,例如轻量级且与 selenium 完美集成的Phantomjs

from selenium import webdriver
driver=webdriver.PhantomJS('your pahtomjs exe file locaiton')
于 2013-07-29T05:07:38.890 回答
0

如果终于找到答案:

首先,首先要做这些:
注意正确设置火狐驱动路径。

接着:

sudo apt-add-repository ppa:mozillateam/firefox-next
sudo apt-get update
sudo apt-get install firefox xvfb
Xvfb :10 -ac &
export DISPLAY=:10

最后运行这个命令,看看我们的实现是否有任何错误。

火狐

如果没有任何输出,只需单击ctrl+c
好的,然后编写此代码。

from selenium import webdriver

class FireFoxLoadTest:
    def __init__(self):
        # 1 - Load a fire fox web driver
        self.driver = webdriver.Firefox()

    def do_test(self, url):
        # 2 - Start to check url on the fire fox browser
        result = self.driver.get(url)
        self.driver.quit()
        return self.result

fire_fox = FireFoxLoadTest()
res = fire_fox.do_test('http://www.google.com')
print(res)
于 2017-09-14T08:04:24.043 回答
0

无头 Firefox 正在取得进展。

从 2017 年 4 月 21 日起,https://adriftwith.me/coding/2017/04/21/headless-slimerjs-with-firefox/

tl;dr Firefox Nightly on Linux 支持无头运行 SlimerJS。
更多平台和完整的无头 Firefox 即将推出。

于 2017-07-03T08:56:35.577 回答