如何从 Python 以隐身模式打开 chrome

how to open chrome in incognito mode from Python

这在 powershell 中有效:

Start-Process chrome.exe -ArgumentList @( '-incognito', 'www.foo.com' )

如何从 Python 实现?

使用os模块执行命令。

import os
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -ArgumentList @( '-incognito', 'www.foo.com'" )

有关 os.system 的更多信息,请参见 here

import subprocess
subprocess.Popen(["C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "-incognito", "www.google.com"])

在我的计算机上,intboolstring 的方法不起作用,另一种更全功能的方法是使用子进程模块中的 call(),但如果命令更改,仍然可以使用 system()。

from subprocess import call
call("\"C:\Path\To\chrome.exe\" -incognito www.foo.com", shell=True)

或使用 system():

from os import system
system("\"C:\Path\To\chrome.exe\" -incognito www.foo.com")

也可以仅使用 "chrome.exe -incognito www.foo.com" 启动 chrome,如果 chrome 添加到路径或通过 运行 通过 powershell 的命令,如下所示:

system("powershell -C Start-Process chrome.exe -ArgumentList @( '-incognito', 'www.foo.com' )")

尽管这种方法比添加 chrome.exe 到路径要慢得多。

Python 使用网络浏览器

在 chrome 中打开隐身模式的脚本
import webbrowser
url = 'www.google.com'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --incognito'
webbrowser.get(chrome_path).open_new(url)

此代码有效。它开始了 新的隐身标签,然后切换 控制新标签页的驱动程序

def incognito():
    global driver
    driver = webdriver.Chrome()
    driver.get('https://www.google.com')
    search=driver.find_element_by_id('lst-ib')
    incognito=search.send_keys(Keys.CONTROL+Keys.SHIFT+'N')
    driver.switch_to_window(driver.window_handles[-1])
    driver.get('https://web.whatsapp.com/')
    time.sleep(5)