Python - 使用Selenium在私密模式下启动Firefox

15

我有以下脚本:

#!/usr/bin/python3
from selenium import webdriver
import time

def getProfile():
    profile = webdriver.FirefoxProfile()
    profile.set_preference("browser.privatebrowsing.autostart", True)
    return profile

def main():
    browser = webdriver.Firefox(firefox_profile=getProfile())

    #browser shall call the URL
    browser.get("http://www.google.com")
    time.sleep(5)
    browser.quit()

if __name__ == "__main__":
    main()

如何管理Firefox以隐私模式启动?


1
@Louis 我之前只看了问题。现在看了答案,我必须同意你的观点,另一个答案更好。 - Uyghur Lives Matter
我认为应该关闭https://dev59.com/rl4c5IYBdhLWcg3wssFs。 - Nakilon
1个回答

23

参考@Laas在如何在Watir中模拟私人浏览体验?(Selenium)的观点:

Selenium等同于启用了隐私浏览。

“隐私浏览”的定义为:

隐私浏览允许您在浏览互联网时不保存有关您访问过哪些站点和页面的任何信息。

因此,每次通过selenium webdriver启动firefox时都会创建一个全新的匿名配置文件,您实际上正在隐私浏览


如果您仍然想在Firefox中强制使用隐私模式,请将browser.privatebrowsing.autostart配置选项设置为true

from selenium import webdriver

firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)

driver = webdriver.Firefox(firefox_profile=firefox_profile)

另外,请参见:


Firefox在处理私密浏览时有技术上的差异。当Firefox的变体在私密浏览下强制执行某些行为时,模拟这些差异非常重要,而不仅仅是“不保存任何信息”。值得注意的是,扩展程序的处理方式也大不相同。 - ndm13
1
@ndm13 好的,感谢反馈。已更新答案。 - alecxe
1
复制/粘贴这段代码在我这里不起作用(最新的Linux/Mint发行版)。除了没有在隐身模式下启动之外,一切都正常。有什么想法吗? - Olivier Pons
TypeError: __init__() got an unexpected keyword argument 'firefox_profile' - axolotl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接