Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

python - How to hide Chromedriver console window?

I have a simple Python script which uses selenium and webdriver to open up Facebook in a Chrome window and log in automatically. When I run it, the Chromedriver console window opens up and stays open even after the entire program has finished execution, until I close it myself.

Is there a way to hide this console window? I have tried keeping a ".pyw" extension for my script, but that doesn't help since it's not the script's console window but the Chromedriver subprocess' console window that I wish to hide.

I couldn't find any resources on this. I think I might need to modify the chrome webdriver source code, but I don't know how. This is my code:

from selenium import webdriver
import sys

driver = webdriver.Chrome("C:Python27Scriptschromedriver.exe")

driver.get("https://www.facebook.com")

email = driver.find_element_by_id("email")
passwd = driver.find_element_by_id("pass")

email.clear()
passwd.clear()

email.send_keys("[email protected]")
passwd.send_keys("examplepassword")

passwd.submit()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To hide the webdriver console window, I had to edit the Libsite-packagesseleniumwebdrivercommonservices.py in my case but I was using PhantomJS. PhantomJS imports and uses this file to start its process. Basically, I added the following creation flag to the Start method:

def start(self):
    """
    Starts the Service.

    :Exceptions:
     - WebDriverException : Raised either when it can't start the service
       or when it can't connect to the service
    """
    try:
        cmd = [self.path]
        cmd.extend(self.command_line_args())
        self.process = subprocess.Popen(cmd, env=self.env,
                                        close_fds=platform.system() != 'Windows',
                                        stdout=self.log_file, stderr=self.log_file, creationflags=CREATE_NO_WINDOW)
    except TypeError:
        raise` in bold.

Also add to the imports this line from win32process import CREATE_NO_WINDOW

This should also work for the Chrome webdriver, as its service.py also imports this very same file, though I have not had time to try.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...